コード生成AI プロンプト例 laravel 12 担当者マスタ CRUDアプリ

コード生成AI プロンプト例 laravel 12 担当者マスタ CRUDアプリ

生成AI で laravel 12 livewire 担当者マスタ CRUDアプリを作る

laravel12 の starter kit で、livewireを使った 担当者マスタ管理を行うマスタメンテナンス(登録、修正、削除、一覧)の画面を作る。

以下のchatGPTの命令書(プロンプト)より、コード自動生成してもった結果、いろいろエラーは出た物のエラーも都度chatGPTに問合せ、繰り替えしコーディング、レビューを行うイメージで作ったアプリです。

# 命令書:
あなたはlaravelエンジニアです。
以下の制約条件に従ってコードを作成してください。

# 制約条件:
・laravelでCURDアプリを作成する手順や設定、ソースコードの生成の依頼
・DBはSQLiteを使用
・Laravelのバージョンは12を使用
・laravel starter kit は、livewire を使用
・PHPのバージョンは8.2を使用
・Windows環境での開発
・Laravelのインストールからモデル、マイグレーション、コントローラー、ルーティング、ビューの作成までの手順やコードを詳細に記載してください
・必要なパッケージのインストールや設定ファイルの編集も含める
・テーブル名は担当者マスタ、テーブルIDは emp、項目IDは id , name , email
・ビューはシンプルでレスポンシブデザインなCRUD操作を行う詳細なソースコードを生成

# 手順の例
・Laravel 新規プロジェクト作成は、laravel new laravel12-app-livewire コマンドを使用
・laravel 環境.envなど設定の手順
・モデル、マイグレーション作成の手順
・マイグレーション実行(テーブル作成)
・コントローラーとリソースCRUD作成
・ルート設定
・コントローラー編集
・モデルにfillable追加
・ビュー作成。詳細な一覧画面、新規登録・編集画面や削除処理のソースコードを生成
・サーバ起動
・その他、必要な編集などあれば指示ください

laravel new laravel12-app-livewire
cd laravel12-app-livewire

以下のパッケージインストールは実行しない。starter kit でlivewire 済みなので。

3. 必要なパッケージのインストール

Livewireスターターキット(Breeze)をインストール
※ BreezeはLivewire, Blade両方サポート

bashコピーする編集するcomposer require laravel/breeze --dev
php artisan breeze:install livewire
npm install
npm run build

モデル&マイグレーション作成などchatGPTの指示に従い実行していき、生成されたコードを貼り付けながらエラーが出て、エラーも問合せしながら解決していき最終的に。サーバーを起動してアプリ完成。

composer run dev

http://localhost:8000/emp

ポップアップで入力画面が表示される仕組み。

最終的なソースです。

database\migrations\2025_07_07_073155_create_emps_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('emps', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('emps');
    }
};

app\Models\Emp.php

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Emp extends Model
{
    use HasFactory;
    protected $table = 'emps';
    protected $fillable = ['name', 'email'];
}

app\Livewire\EmpCrud.php

<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Emp;

class EmpCrud extends Component
{
    public $emps, $name, $email, $emp_id;
    public $isOpen = false, $isEdit = false;

    public function render()
    {
        $this->emps = Emp::all();
        return view('livewire.emp-crud');
    }

    public function create()
    {
        $this->resetInputFields();
        $this->isOpen = true;
        $this->isEdit = false;
    }

    public function edit($id)
    {
        $emp = Emp::findOrFail($id);
        if (!$emp) {
            session()->flash('message', '指定されたデータが存在しません');
            return;
        }
        $this->emp_id = $id;
        $this->name = $emp->name;
        $this->email = $emp->email;
        $this->isOpen = true;
        $this->isEdit = true;
    }

    public function store()
    {
        $this->validate([
            'name' => 'required',
            'email' => 'required|email|unique:emps,email,' . $this->emp_id,
        ]);

        Emp::updateOrCreate(['id' => $this->emp_id], [
            'name' => $this->name,
            'email' => $this->email,
        ]);

        session()->flash('message',
            $this->emp_id ? '更新しました。' : '新規登録しました。'
        );

        $this->closeModal();
        $this->resetInputFields();
    }

    public function delete($id)
    {
        Emp::find($id)->delete();
        if (!$emp) {
            session()->flash('message', '指定されたデータが存在しません');
            return;
        }
        session()->flash('message', '削除しました。');
    }

    private function resetInputFields()
    {
        $this->name = '';
        $this->email = '';
        $this->emp_id = '';
    }

    public function closeModal()
    {
        $this->isOpen = false;
    }
}

resources\views\livewire\emp-crud.blade.php

<div>
    {{-- Care about people's approval and you will be their prisoner. --}}
<div class="max-w-2xl mx-auto p-4">
    <h1 class="text-2xl font-bold mb-4">担当者マスタ管理</h1>

    @if (session()->has('message'))
        <div class="mb-2 text-green-600">{{ session('message') }}</div>
    @endif

    <button wire:click="create" class="bg-blue-600 text-white px-4 py-2 rounded mb-3">新規登録</button>

    <table class="w-full border">
        <thead class="bg-gray-200">
            <tr>
                <th class="p-2 border">ID</th>
                <th class="p-2 border">名前</th>
                <th class="p-2 border">メール</th>
                <th class="p-2 border">操作</th>
            </tr>
        </thead>
        <tbody>
            @foreach($emps as $emp)
                <tr>
                    <td class="p-2 border">{{ $emp->id }}</td>
                    <td class="p-2 border">{{ $emp->name }}</td>
                    <td class="p-2 border">{{ $emp->email }}</td>
                    <td class="p-2 border">
                        <button wire:click="edit({{ $emp->id }})" class="bg-yellow-400 px-2 py-1 rounded">編集</button>
                        <button wire:click="delete({{ $emp->id }})" class="bg-red-500 text-white px-2 py-1 rounded" onclick="return confirm('本当に削除しますか?')">削除</button>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>

    <!-- モーダル(登録・編集) -->
    @if($isOpen)
        <div class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-30 z-50">
            <div class="bg-white p-6 rounded shadow w-96">
                <h2 class="text-lg font-semibold mb-3">{{ $isEdit ? '編集' : '新規登録' }}</h2>
                <form wire:submit.prevent="store">
                    <div class="mb-3">
                        <label class="block text-sm">名前</label>
                        <input type="text" wire:model="name" class="w-full border p-2 rounded" required>
                        @error('name') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
                    </div>
                    <div class="mb-3">
                        <label class="block text-sm">メール</label>
                        <input type="email" wire:model="email" class="w-full border p-2 rounded" required>
                        @error('email') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
                    </div>
                    <div class="flex justify-end gap-2">
                        <button type="button" wire:click="closeModal" class="px-4 py-2 border rounded">閉じる</button>
                        <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded">{{ $isEdit ? '更新' : '登録' }}</button>
                    </div>
                </form>
            </div>
        </div>
    @endif
</div>

</div>

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use Livewire\Volt\Volt;

Route::get('/', function () {
    return view('welcome');
})->name('home');

Route::view('dashboard', 'dashboard')
    ->middleware(['auth', 'verified'])
    ->name('dashboard');

Route::middleware(['auth'])->group(function () {
    Route::redirect('settings', 'settings/profile');

    Volt::route('settings/profile', 'settings.profile')->name('settings.profile');
    Volt::route('settings/password', 'settings.password')->name('settings.password');
    Volt::route('settings/appearance', 'settings.appearance')->name('settings.appearance');
});

Route::get('/emp', \App\Livewire\EmpCrud::class)->name('emp.index');

require __DIR__.'/auth.php';

エラーは色々ありましたが、

SQLSTATE[HY000]: General error: 1 no such table: emp (Connection: sqlite, SQL: select count(*) as aggregate from "emp" where "email" = test@test and "id" <> )

モデル内にemp記述あり。emp→empsでエラー解消。

Call to a member function initials() on null
や
Attempt to read property "name" on null

sidebar.blade.php のnullの場合の処理を入れる。

<div>
  ログインユーザー:{{ optional(Auth::user())->name }}
</div>

や

 optional(Auth::user())->initials()

以上です。

登録、修正、削除、一覧するCRUDアプリを約1時間で作る事ができました。

コーディングの流れは、

  • 命令書を大枠作りたい、生成してほしい指示書をプロンプト
  • コードを貼り付け、動かしてみて、エラーが出たら、続けてchatGPTに張り付け、解消方法を教えてくれるので、都度コードを修正しながら。