laravelのリソースコントローラについてのメモです。
リソースコントローラ
リソースコントローラを使うとアプリの基本的な操作であるCRUD(作成、一覧表示、編集、削除)などのアクションやそのルーティングが自動的にされます。
例えばusersのリソースコントローラだと下のようなアクションが自動で作られます。
HTTPメソッド | URI | アクション | ルート名 |
---|---|---|---|
GET | /users | index | users.index |
GET | /users/create | create | users.create |
POST | /users | store | users.store |
GET | /users/{user} | show | users.show |
GET | /users/{user}/edit | edit | users.edit |
PUT/PATCH | /users/{user} | update | users.update |
DELETE | /users/{user} | destroy | users.destroy |
作成
コントローラをつくるartisanコマンドに--resource
をつけます。
php artisan make:controller UsersController --resource
すると自動的にコントローラ内にこれらのアクションが用意されます。
UsersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
ルーティング
web.php
Route::resource('users', 'UsersController');
これだけですべてのアクションの紐づけができます。
また使うアクションを限定することもできます。作成、一覧表示のみを行う場合↓
web.php
//作成、一覧表示のみを行う場合
Route::resource('users', 'UsersController', ['only' => ['index', 'create', 'store', 'show']]);