laravel5.5 middleware接收参数的写法

      • 场景
      • 原因

场景

  • 在做api token的时候 配置api路由的时候 middleware需要指定api guard ‘middleware’ => [‘auth:api’]; 之前只是知道需要这样做 但是不知道理由;
  • 今天在laravel官网找到了答案

原因

  • 这样做是为了传递参数'api guard' ;指定auth middleware指定的guard; 因为它是默认web(文件config/auth.php)
  • \Illuminate\Auth\Middleware\Authenticate::class handle函数
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $this->authenticate($guards);

        return $next($request);
    }

[官网资料](https://laravel.com/docs/5.5/middleware#middleware-parameters

Middleware can also receive additional parameters. For example, if your application needs to verify that the authenticated user has a given “role” before performing a given action, you could create a CheckRole middleware that receives a role name as an additional argument.
Additional middleware parameters will be passed to the middleware after the $next argument:

Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:



namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    /**
     * Handle the incoming request.
     *
     * @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)) {
            // Redirect...
        }

        return $next($request);
    }

}

Route::put('post/{id}', function ($id) {
    //
})->middleware('role:editor');

你可能感兴趣的:(laravel)