How to Implement Multiple Authentication Guards in Laravel 8 www.bacancytechnology.com
Introduction
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. To handle many users. A single application is used for customers and employees to connect company products and services. An application that works with lots of departments. 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.
Tutorial Goal: Multiple Authentication Guards in Laravel 8
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.
Initial Set-Up
Create the application by the below command
composer create-project --prefer-dist laravel/laravel laravel_guard cd laravel_guard
Open. env file and update the database details
Create Migration and Model
Use the below command to create migration and Model for Admin and Blog
php artisan make:model Admin -m php artisan make:model Blog -m 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.
Define Guards
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
// Admin.php <?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; class Admin extends Authenticatable { protected $guard = 'admin'; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; }
Within app/model folder, open Blogger.php then update guards with blog and fillable array with fields names
// Blogger.php <?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; class Blog extends Authenticatable { protected $guard = 'blog'; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; }
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, ], ],
Set-Up Controllers
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.
Update Register Controller
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.
//RegisterController
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:us ers', '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'); } }
Set-Up Authentication
Now, install Authentication for Laravel Set url in web.php file Create blade file for admin and blogger dashboard
Set-Up Middleware for Guards
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); } }
Set-Up Exceptions
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
Run the application by using the below command
php artisan serve
If you want to clone the repository here’s the source code: multiple-guardauthentication
Conclusion
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.
Thank You
www.bacancytechnology.com