最近在使用laravel5.5,利用其實現了一個功能,下面分享給大家,這篇文章主要給大家介紹了關於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
<?phpnamespace 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'); } }
完成
總結
您可能感興趣的文章:
PHP二維數組實現去除重複項的方法
Thinkphp5行為使用方法的匯總
ajax+php實現無重新整理驗證手機號的執行個體講解