您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關Laravel 5.5基于內置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'); } }
關于“Laravel 5.5基于內置Auth模塊實現前后臺登陸的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。