ระบบจะกำหนดค่า Routing และสร้าง Controllers แบบ CRUD ให้อัตโนมัติ เริ่มจากสร้าง Resource Controllers ด้วยคำสั่งด้านล่าง
1 |
php artisan make:controller DepartmentController --resource |
หากต้องการเชื่อมกับ Model ด้วย ให้ใช้คำสั่งด้านล่าง
1 |
php artisan make:controller DepartmentController --resource --model=Department |
ระบบจะสร้างไฟล์ app/Http/Controllers/DepartmentController.php ขึ้นมา
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class DepartmentController 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) { // } } |
จากนั้นให้เราไปกำหนด Route ในไฟลฟ์ routes/web.php
1 |
Route::resource('departments', 'DepartmentController'); |
หรือสามารถกำหนดได้หลายๆ Resource Controllers
1 2 3 4 |
Route::resources([ 'department' => 'DepartmentController', 'posts' => 'PostController' ]); |
Verb | URI | Action | Route Name |
---|---|---|---|
GET | /departments |
index | departments .index |
GET | /departments/create |
create | departments .create |
POST | /departments |
store | departments .store |
GET | /departments/{department} |
show | departments .show |
GET | /departments/{department}/edit |
edit | departments .edit |
PUT/PATCH | /departments/{department} |
update | departments .update |
DELETE | /departments/{department} |
destroy | departments .destroy |
1 2 3 4 5 6 7 |
Route::resource('departments', 'DepartmentController')->only([ 'index', 'show' ]); Route::resource('departments', 'DepartmentController')->except([ 'create', 'store', 'update', 'destroy' ]); |
ดูเพิ่มเติม https://laravel.com/docs/master/controllers#basic-controllers
ป้ายกำกับ:Controllers, laravel, Resource Controllers