Laravel 5.5基于内置的Auth模块实现前后台登陆详解
程序员文章站
2022-05-14 23:25:30
前言
本文主要介绍了关于laravel 5.5基于内置的auth模块实现前后台登陆的相关内容,更多关于auth模块的内容大家可以参考这篇文章:
下面话不多说了,来一起看...
前言
本文主要介绍了关于laravel 5.5基于内置的auth模块实现前后台登陆的相关内容,更多关于auth模块的内容大家可以参考这篇文章:
下面话不多说了,来一起看看详细的介绍吧。
方法如下:
步骤1:生成auth
在项目建立完成后,生成内置auth组件:
php artisan make:auth
步骤2:添加guard
打开config\auth.php,为方便前后台用户切换,项目共用users表
'guards' => [ //... 'admin' => [ 'driver' => 'session', 'provider' => 'users', ], //... ],
步骤3:实现基类
class admincontroller extends basecontroller { use authorizesrequests, dispatchesjobs, validatesrequests; public function __construct() { $this->middleware('auth:admin'); } }
步骤4:实现后台登陆控制器
新建appcontrollersadminlogincontroller.php
<?php namespace app\http\controllers\admin; use app\http\controllers\controller; use illuminate\support\facades\auth; use illuminate\foundation\auth\authenticatesusers; use illuminate\http\request; class logincontroller extends controller { /* |-------------------------------------------------------------------------- | login controller |-------------------------------------------------------------------------- | | this controller handles authenticating users for the application and | redirecting them to your home screen. the controller uses a trait | to conveniently provide its functionality to your applications. | */ use authenticatesusers; /** * where to redirect users after login. * * @var string */ protected $redirectto = '/admin'; /** * create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest:admin')->except('logout'); } /** * 重写登陆页面 * @return \illuminate\contracts\view\factory|\illuminate\view\view */ public function showloginform() { return view('backend.login'); } /** * 重写退出方法 * @param request $request * @return \illuminate\http\redirectresponse|\illuminate\routing\redirector */ public function logout(request $request) { $this->guard()->logout(); $request->session()->flush(); $request->session()->regenerate(); return redirect('/admin/login'); } /** * 重写guard认证 * @return mixed */ protected function guard() { return auth::guard('admin'); } }
步骤5:实现登陆后跳转到不同路径
app\middleware\redirectifauthenticated.php
public function handle($request, closure $next, $guard = null) { if (auth::guard($guard)->check()) { $path = $guard ? '/admin' : '/home'; return redirect($path); } return $next($request); }
步骤6:实现未通过认证跳转不同登陆页
app\exceptions\handler.php
/** * 重写实现未认证用户跳转至相应登陆页 * @param \illuminate\http\request $request * @param authenticationexception $exception * @return \illuminate\http\jsonresponse|\illuminate\http\redirectresponse */ protected function unauthenticated($request, authenticationexception $exception) { if($request->expectsjson()){ return response()->json(['message' => $exception->getmessage()], 401); }else{ return in_array('admin', $exception->guards()) ? return redirect()->guest('/admin/login') : redirect()->guest('login'); } }
完成
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。
下一篇: 微信小程序日历效果