Laravel基本
更新日 2025-06-03 16:14:32
laravel
コントローラ
コントローラの生成方法
コントローラ生成php artisan make:controller PhotoController
リソースコントローラの場合
php artisan make:controller PhotoController --resource
ルートの登録
ルートの登録方法
routes/web.phpにルートを登録する単一アクション
Route::get('/about', [App\Http\Controllers\PageController::class, 'about']);
POST / PUT / DELETE など
Route::post('/submit', [FormController::class, 'submit']);
Route::put('/update/{id}', [ItemController::class, 'update']);
Route::delete('/delete/{id}', [ItemController::class, 'destroy']);
コントローラでグループ化
Route::controller(PostController::class)->group(function () {
Route::get('/posts', 'index'); // 一覧表示
Route::get('/posts/{id}', 'show'); // 詳細表示
Route::post('/posts', 'store'); // 作成
Route::put('/posts/{id}', 'update'); // 更新
Route::delete('/posts/{id}', 'destroy'); // 削除
});
ルートグループ
Route::middleware(['auth'])->group(function () {
Route::get('/profile', [UserController::class, 'profile']);
});
リソースで設定する場合
Route::resource('photos', 'PhotoController');
リソースコントローラにより処理されるアクション
動詞 URI アクション ルート名
GET /photos index photos.index
GET /photos/create create photos.create
POST /photos store photos.store
GET /photos/{photo} show photos.show
GET /photos/{photo}/edit edit photos.edit
PUT/PATCH /photos/{photo} update photos.update
DELETE /photos/{photo} destroy photos.destroy
ビュー
ビューの生成方法
layouts/app.blade.php<html>
<head>
<title>アプリ名 - @yield('title')</title>
</head>
<body>
@section('sidebar')
ここがメインのサイドバー
@show
<div class="container">
@yield('content')
</div>
</body>
</html>
child.blade.php
@extends('layouts.app')
@section('title', 'Page Title')
@section('sidebar')
@@parent
<p>ここはメインのサイドバーに追加される</p>
@endsection
@section('content')
<p>ここが本文のコンテンツ</p>
@endsection
モデル
モデルの生成方法
モデル生成php artisan make:model Flight
Modelsディレクトリに作成する場合
php artisan make:model Models/Flight
マイグレーションも出力する場合
php artisan make:model Flight --migration
php artisan make:model Flight -m //省略形
マイグレーション
テーブル作成のマイグレーション
テーブルの生成php artisan make:migration create_companies_table
オプション付き
php artisan make:migration create_companies_table --create=companies
このオプションを付けると、Laravelが自動で Schema::create() を生成してくれますテーブル更新のマイグレーション
テーブル更新php artisan make:migration add_age_to_users_table
オプション付き
php artisan make:migration add_age_to_users_table --table=users
このオプションを使うと Schema::table() の構文でマイグレーションが生成されます