An experienced laravel developer has definitely used ‘multiple guards’ frequently. But, in case you are newly introduced to the technology then maybe the concept of multiple authentication guards won’t be that much familiar.
There are lots of reasons for using multiple authentications in laravel applications.
So if you’re looking for a tutorial on how to implement multiple authentication guards in Laravel 8 then here is a step-by-step guide for you. In this application, we are using separate login and table for admin and blog authentication.
Before starting the development, let us first see the video on how multi-guard authentication works. In our demo, we have used two logins, one for the blogger and one for the admin.
Create the application by the below command
Open. env file and update the database details
Use the below command to create migration and Model for Admin and Blog
Update the migration file of the admin and blog like the users’ migration table, or you can also extend the table by adding fields needed for the application.
Less Hassle. Core Development.
Hire Laravel developer from us to future-proof your custom app development requirement; so you can exclusively focus on other core business activities.
Moving towards the main section of our tutorial: multiple authentication guards in Laravel 8. Guards define how admin and blogger are authenticated for each request. Our application will have two guards Admin and Blogger; after defining the guards set their providers. When we use these guards it tells what to use for authentication or validation. Open Admin.php file in app/model folder. Update guard as admin and fillable array with fields names
Within app/model folder, open Blogger.php then update guards with blog and fillable array with fields names
Open config/auth.php for adding guards. We’ve added two guard: admin and blog and update their provider’s array.
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'blog' => [ 'driver' => 'session', 'provider' => 'blog', ], ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => App\Models\Admin::class, ], 'blog' => [ 'driver' => 'eloquent', 'model' => App\Models\Blog::class, ], ],
Open Login controller within Auth Folder.
For guard operation, we will update the existing login controller inside the auth folder or create a new controller. We need to define all guests in the controller, if the blogger or admin successfully login, it will redirect to the intended route.
middleware('guest')->except('logout'); $this->middleware('guest:admin')->except('logout'); $this->middleware('guest:blog')->except('logout'); } public function showAdminLoginForm() { return view('auth.login', ['url' => 'admin']); } public function login(Request $request) { $this->validate($request, [ 'email' => 'required|email', 'password' => 'required|min:6' ]); if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) { return redirect()->intended('/admin'); }blogg return back()->withInput($request->only('email', 'remember')); } public function showBloggerLoginForm() { return view('auth.login', ['url' => 'blog']); } public function bloggerLogin(Request $request) { $this->validate($request, [ 'email' => 'required|email', 'password' => 'required|min:6' ]); if (Auth::guard('blog')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) { return redirect()->intended('/blog'); } return back()->withInput($request->only('email', 'remember')); } }
Login function checks admin credentials and redirect and also bloglogin function checks blog credentials and redirect to the intended route.
In this section of implementing multiple authentication guards in Laravel 8 we will simply update the RegisterController. For that, open RegisterController and add the below code.
middleware('guest'); $this->middleware('guest:admin'); $this->middleware('guest:blog'); } protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:6|confirmed', ]); } public function showAdminRegisterForm() { return view('auth.register', ['url' => 'admin']); } public function showBloggerRegisterForm() { return view('auth.register', ['url' => 'blog']); } protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); } protected function createAdmin(Request $request) { $this->validator($request->all())->validate(); Admin::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); return redirect()->intended('login/admin'); } protected function createBlogger(Request $request) { $this->validator($request->all())->validate(); Blog::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); return redirect()->intended('login/blog'); } }
Open RedirectIfAuthenticated.php file and update with the below code. Here, the middleware gets guard as a parameter and redirects to the intended route
check()) { return redirect('/admin'); } if ($guard == "blog" && Auth::guard($guard)->check()) { return redirect('/blog'); } if (Auth::guard($guard)->check()) { return redirect('/home'); } return $next($request); } }
Move to the authentication exception handler. This is to ensure that when an admin tries to login /admin they are redirected to /login/admin or the same for /blog. Open app/Exceptions and use the following code.
expectsJson()) { return response()->json(['error' => 'Unauthenticated.'], 401); } if ($request->is('admin') || $request->is('admin/*')) { return redirect()->guest('/login/admin'); } if ($request->is('blog') || $request->is('blog/*')) { return redirect()->guest('/login/blog'); } return redirect()->guest(route('login')); } }
Run the application by using the below command
If you want to clone the repository here’s the source code: multiple-guard-authentication
So, this was about how to implement multiple authentication guards in Laravel 8. I hope the purpose of the tutorial has been served the way you’ve expected. Feel free to contact us if you have any suggestions or feedbacks. Visit Laravel tutorials page for more such step-by-step guidelines. Each tutorials will provide github repository that you can clone and play around with the code.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.