我建议您制作自己的中间件,您可以在其中以默认方法handle 编写您的身份验证代码。然后您只需要调用该中间件即可获得任一用户的身份验证。
在app/Http/Middleware/CustomAuthentiation.php 内部制作一个中间件
并在那里写下你的逻辑,就像这样 sn-p:
class CustomAuthentiation
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
// Write your authentication code here and then in last lines, if all is good, forward the execution ahead. Like :
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
然后将其添加到 app/Http/Kernel.php 的 Kernel.php 文件中的 $routeMiddleware 数组中,如下所示:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'myAuth' => \App\Http\Middleware\CustomAuthentiation::class // Here is your middleware..
];
然后你可以像这样在routes/web.php 中绑定这个中间件:
Route::middleware('myAuth')->post('login', 'LoginController@LoginUser');
希望这会有所帮助。