指定中间件的方式
1.为所有的路由同时指定中间件
在\app\Http\Kernel.php文件中注册全局中间件
protected $middleware = [ // \App\Http\Middleware\TrustHosts::class, \App\Http\Middleware\TrustProxies::class, \Fruitcake\Cors\HandleCors::class, \App\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ];
2.为某个路由文件中的所有路由同时指定中间件
在app\Providers\RouteServiceProvider.php文件中指定路由文件和中间件
public function boot() { $this->configureRateLimiting(); $this->routes(function () { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); }); }
3.为某几个路由同时指定中间件
在路由定义文件中使用group
Route::middleware(['auth','agent.mobile'])->group(function () { Route::get('/audit/home', [App\Http\Controllers\HomeController::class, 'mobileAudit'])->name('audit.home'); Route::get('/audit/employees', [App\Http\Controllers\Admin\EmployeeInfoController::class, 'mobileAuditGetInfo'])->name('audit.employees'); Route::get('/audit/employee/{id}', [App\Http\Controllers\Admin\EmployeeInfoController::class, 'mobileAuditGetInfoById'])->name('audit.employee'); Route::get('/audit/attendance', [App\Http\Controllers\Admin\AttendanceController::class,'getAttendanceForManage'])->name('audit.attendance'); Route::get('/audit/leaves', [App\Http\Controllers\Admin\LeaveController::class,'auditIndex'])->name('audit.leaves'); Route::get('/audit/user', function (){return view('mobile.examination.user.index');})->name('audit.user'); });
4.为某个路由指定中间件
在路由文件中直接指定
Route::get('admin/profile', function () { // })->middleware('auth'); Route::get('/', function () { // })->middleware('first', 'second'); use App\Http\Middleware\CheckAge; Route::get('admin/profile', function () { // })->middleware(CheckAge::class);
5.为某个控制器相关的所有路由指定中间件
在控制器的构造函数中指定
class UserController extends Controller { /** * 实例化一个新的控制器实例 * * @return void */ public function __construct() { $this->middleware('auth'); $this->middleware('log')->only('index'); $this->middleware('subscribed')->except('store'); } }