Laravel 8 中間件參數(shù)

2021-07-16 17:58 更新

中間件還可以接收額外的參數(shù)。例如,如果你的應(yīng)用程序需要在執(zhí)行給定操作之前驗(yàn)證用戶是否為給定的「角色」, 你可以創(chuàng)建一個(gè) CheckRole 中間件,由它來接收「角色」名稱作為附加參數(shù)。

附加的中間參數(shù)會(huì)在 $next 參數(shù)之后傳遞給中間件:

<?php

namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    /**
     * 處理傳入的請求
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $role
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole($role)) {
            // 重定向...
        }

        return $next($request);
    }

}

定義路由時(shí)通過一個(gè) : 來隔開中間件名稱和參數(shù)來指定中間件參數(shù)。多個(gè)參數(shù)就使用逗號(hào)分隔:

Route::put('post/{id}', function ($id) {
    //
})->middleware('role:editor');
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)