參考 http://mattallan.org/2016/setting-the-guard-per-route-in-laravel/php
監聽 RouteMatched 事件, 設置默認的 guardlaravel
<?php $this->app['router']->matched(function (\Illuminate\Routing\Events\RouteMatched $event) { $route = $event->route; if (!array_has($route->getAction(), 'guard')) { return; } $routeGuard = array_get($route->getAction(), 'guard'); $this->app['auth']->resolveUsersUsing(function ($guard = null) use ($routeGuard) { return $this->app['auth']->guard($routeGuard)->user(); }); $this->app['auth']->setDefaultDriver($routeGuard); });
<?php Route::group(['guard' => 'api'], function () { Route::get('/api/whoami', function () { return Auth::user()->toJson(); }); }); Route::group(['guard' => 'web'], function () { Route::get('/whoami', function () { $name = Auth::user()->name; return "hello {$name}!"; }); });
另外一種思路, 寫一箇中間件來設置默認的 guardweb