/**
* 直接在控制器的构造函数里调用
*
* ProductController constructor.
*/
public function __construct()
{
//由于Get 请求没法使用 FormRequest 做参数验证,因为请求的Body 没有参数,所以想到可以使用中间件对指定的Get方法做参数验证
//控制器里使用中间件的几个场景如下:
//通过 param 中间件控制
// $this->middleware('param')->only('getTag');
// $this->middleware('auth');
// $this->middleware('param')->except('edit');
//直接写一个闭包的middleware,不用全局定义,就不用单独写一个Middleware类了,这样就只用于当前控制器
$this->middleware(function ($request, $next) {
if (empty($request->input('tag'))) {
return response()->json(['message' => 'tag参数必须', 'data' => [], 'code' => 4012]);
}
return $next($request);
})->only('getTag');
}
/**
* 在routes/api.php里定义路由
*/
Route::group([
'prefix' => 'test',
'middleware' => ['auth'],//给组添加中间件
'as' => 'test.',
], function () {
Route::get('sort', [TestController::class, 'index'])->name('test.index')->withoutMiddleware(['auth']);//组中的某些路由不想要中间件,可以通过withoutMiddleware指定
}
);
