In order to replace all request processing logic defined in the form of closures in the routing file, if you want to use control classes to organize these behaviors, the controller can put the relevant request processing logic Composed into a separate class, the controller is stored in the app/Http/Controllers directory.
1. Simply create a controller
//使用php artisan 命令,创建好后会自动加载命名空间,自动基础控制器基类 php artisan make:controller [控制器路径/]控制器名称
2. Classification of controllers
1. Basic controller
//app/http/controller/定义UserController namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Models\User; class UserController extends Controller { /** * 显示指定用户的简介 * * @param int $id * @return \Illuminate\View\View */ public function show($id) { ....... } }
Used in routing:
Route::get('user/{id}', [UserController::class, 'show']);
2. Single behavior controller
//使用命令行方式创建单行为控制器 php artisan make:controller GetName --invokable
namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Models\User; class GetName extends Controller { /** * 显示指定用户的简介 * * @param int $id * @return \Illuminate\View\View */ public function __invoke($id) { ......... } }
Used in routing:
Route::get('user/{id}', GetName::class)
3. Resource controller
//使用命令行方式创建资源控制器 php artisan make:controller UserController --reosurce
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Models\Category; use App\Models\Good; use App\Transformers\GoodTransformer; use Illuminate\Http\Request; class GoodController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { } /** * 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) { } /** * 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) { // } }
Used in routing:
//第二参数为选填,例如当不需要destory()方法时,即可填入 Route::resource('goods',\App\Http\Controllers\Admin\GoodController::class,[ 'except' => 'destroy' ]); Route::resource('goods',\App\Http\Controllers\Admin\GoodController::class,[ 'only' => ['index','show','store','update'] ]);
Related videos Tutorial recommendation: Laravel Video Tutorial
The above is the detailed content of Controllers in Laravel. For more information, please follow other related articles on the PHP Chinese website!