0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

🐘【超入門】XAMPP+ComposerでLaravelを始める

Posted at

✅ 前提環境

  • Windows(XAMPPインストール済み)
  • Apache / MySQL が起動できる
  • Composer インストール済み
  • VS Code などのエディタ

確認コマンド:

php -v
composer -V

🧭 ゴールの全体像

  1. XAMPP起動(Apache / MySQL)
  2. phpMyAdminで DB作成(laravel_app
  3. Composerで Laravelプロジェクト作成
  4. .env を編集して DB接続
  5. マイグレーション → tasks テーブル作成
  6. モデル・コントローラ・ビュー作成
  7. php artisan serve で起動
  8. 追加・一覧・削除を確認

1. DB作成(phpMyAdmin)

http://localhost/phpmyadmin/ を開いて

  • データベース → 新規作成
  • 名前:laravel_app
  • 照合順序:utf8mb4_general_ci

2. Laravel新規作成(Composer)

composer create-project laravel/laravel my-laravel-app
cd my-laravel-app
php artisan --version

3. .env 編集(DB接続)

プロジェクト直下の .env を編集します。

APP_NAME="MiniCRUD"
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=

SESSION_DRIVER=file   # ← 初心者は file が安全
CACHE_STORE=file
QUEUE_CONNECTION=sync

反映コマンド:

php artisan key:generate
php artisan config:clear

4. マイグレーション作成

php artisan make:migration create_tasks_table --create=tasks

生成された database/migrations/xxxx_create_tasks_table.php を編集:

Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('body')->nullable();
    $table->timestamps();
});

実行:

php artisan migrate

5. モデル作成

php artisan make:model Task

app/Models/Task.php

class Task extends Model
{
    protected $fillable = ['title', 'body'];
}

6. コントローラ作成

php artisan make:controller TaskController

app/Http/Controllers/TaskController.php

class TaskController extends Controller
{
    public function index() {
        $tasks = Task::latest()->get();
        return view('tasks.index', compact('tasks'));
    }

    public function store(Request $request) {
        $validated = $request->validate([
            'title' => ['required','string','max:100'],
            'body'  => ['nullable','string','max:1000'],
        ]);
        Task::create($validated);
        return redirect()->route('tasks.index')->with('status','追加しました!');
    }

    public function destroy(Task $task) {
        $task->delete();
        return redirect()->route('tasks.index')->with('status','削除しました!');
    }
}

7. ルート設定

routes/web.php

use App\Http\Controllers\TaskController;

Route::get('/', fn() => redirect()->route('tasks.index'));
Route::get('/tasks', [TaskController::class, 'index'])->name('tasks.index');
Route::post('/tasks', [TaskController::class, 'store'])->name('tasks.store');
Route::delete('/tasks/{task}', [TaskController::class, 'destroy'])->name('tasks.destroy');

8. ビュー作成

resources/views/tasks/index.blade.php

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>MiniCRUD(Laravel)</title>
  <style>
    body{font-family:system-ui;max-width:900px;margin:32px auto}
    table{width:100%;border-collapse:collapse}
    th,td{border:1px solid #ccc;padding:8px}
    form.inline{display:inline}
  </style>
</head>
<body>
  <h1>📝 MiniCRUD</h1>

  @if(session('status'))
    <p style="color:green">{{ session('status') }}</p>
  @endif

  <form method="post" action="{{ route('tasks.store') }}">
    @csrf
    <input name="title" placeholder="タイトル" required>
    <textarea name="body" placeholder="メモ"></textarea>
    <button>追加</button>
  </form>

  <h2>一覧</h2>
  @if($tasks->isEmpty())
    <p>まだありません</p>
  @else
    <table>
      <tr><th>ID</th><th>タイトル</th><th>メモ</th><th>操作</th></tr>
      @foreach($tasks as $t)
      <tr>
        <td>{{ $t->id }}</td>
        <td>{{ $t->title }}</td>
        <td>{{ $t->body }}</td>
        <td>
          <form class="inline" method="post" action="{{ route('tasks.destroy',$t) }}">
            @csrf @method('DELETE')
            <button>削除</button>
          </form>
        </td>
      </tr>
      @endforeach
    </table>
  @endif
</body>
</html>

9. アプリ起動

php artisan serve

http://127.0.0.1:8000 を開いて…

  • フォームからタイトルを入力 → 追加
  • 下の一覧に表示される
  • 削除で行が消える

🎉 これで Create / Read / Delete が完成です!


🔧 つまずきポイント(対策)

  • Base table already existsphp artisan migrate:fresh
  • sessions テーブルが無いエラー.envSESSION_DRIVER=file に変更
  • EncryptCookies エラーapp/Http/Middleware/EncryptCookies.php が無いときは復旧
  • .env 変更時は必ず → php artisan config:clear

🎯 まとめ

  • XAMPP + Composer でLaravelを立ち上げ
  • .env を正しく設定
  • 5つのファイル(migration, model, controller, route, view)でミニCRUD完成
  • 初学者は SESSION/CACHE/QUEUEはfile/sync にしておくとトラブル回避できる

👉 これで「Laravelってこうやって動くんだ!」を体験できます。
次のステップは 更新(Update機能追加)ページネーション に挑戦してみましょう 🚀

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?