How to setup multiple authentication in Laravel 5.6

* * @param IlluminateHttpRequest $request * @param IlluminateAuthAuthenticationException $exception * @return IlluminateHttpResponse */ protected function unauthenticated($request, AuthenticationException $exception) { if ($request->expectsJson()) { return response()->json(['error' => 'Unauthenticated.'],401); } $guard = array_get($exception->guards(), 0); switch ($guard) { case 'admin': $login = 'admin.login'; break; default: $login = 'login'; break; } return redirect()->guest(route($login)); }Step 12: Set up Middleware for RedirectionTo set up the middleware for redirection after authentication, go to app/Http/Middleware/RedirectIfAuthenticated.php and update the code with the following://public function handle($request, Closure $next, $guard = null){ switch ($guard) { case 'admin' : if (Auth::guard($guard)->check()) { return redirect()->route('admin.home'); } break; default: if (Auth::guard($guard)->check()) { return redirect()->route('home'); } break; } return $next($request);}//Step 12: Set up Authentication ConfigurationTo set up the authentication configuration, go to config/auth.php and update the code with the following://'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ],'admins' => [ 'driver' => 'eloquent', 'model' => AppAdmin::class, ],////'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'admin-api' => [ 'driver' => 'token', 'provider' => 'admins', ], ],////'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => AppUser::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => AppAdmin::class, ], ],////'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, ], 'admins' => [ 'provider' => 'admins', 'table' => 'password_resets', 'expire' => 15, ], ],Step 13: Set up Database Migration Default String LenthTo set up the default string length for the database migration, go to app/Providers/AppServiceProvider.php and update the code with the following:use IlluminateSupportServiceProvider;use IlluminateSupportFacadesSchema;//public function boot() { Schema::defaultStringLength(191); }Step 14: Run the MigrationTo run the migration, enter the command below:php artisan migrateUse tinker to input Admin login credentials:php artisan tinker$admin = new AppAdmin$admin->email = 'admin@app.com'$admin->password = Hash::make(’admin-password’)$admin->save()Congratulations!Hopefully, now you can easily setup Multiple Authentication in Laravel projects..If you need help, just drop a comment and I will get back to you ASAP!The full source code for this tutorial can be found on GitHub.. More details

Leave a Reply