TechvBlogs
Published in

TechvBlogs

How to Implement Multiple Authentication Guards in Laravel 9

Aug 16, 2022, Originally published at techvblogs.com ・14 min read

Eventually, we are going to learn how to create multiple auth (Authentication) in Laravel using guards, and we will also consider other laravel imperatives that are useful to build laravel basic auth app from starting.

In general, Authentication is the security process, and it indicates acknowledging the genuine user with proper account details.

We will develop two users one is an admin, and the other one is a regular user. Based on their roles, we will allow them to access in the app using middleware. Let us begin our work and start building our application.

How to Implement Multiple Authentication Guards in Laravel 9

Before starting the development, let us first see the video on how multi-guard authentication works. In our demo, we used two logins, one for the blogger and one for the admin.

Step 1: Install Laravel Project

First, open Terminal and run the following command to create a fresh laravel project:

or, if you have installed the Laravel Installer as a global composer dependency:

Step 2: Install Laravel UI

Next, you need to run the below command in your terminal

Step 3: Setup Auth Scaffolding with Bootstrap 5

Step 4: Install NPM Dependencies

Run the following command to install frontend dependencies:

After the Update Of Laravel 9.20.0, Laravel replaces Webpack with Vite. You can follow this article for Setup Bootstrap 5 in Laravel 9.

Step 5. Configure Database Details:

After, Installation Go to the project root directory, open the .env file, and set database detail as follow:

Step 6: Create Migration and Model

Use the below command to create migration and Model for Admin and Blog

-m the argument is used to create a migration file.

Update the migration file of the admin like the users’ migration table, or you can also extend the table by adding fields needed for the application.

Step 7: Define Guards

Guards define how the admin is authenticated for each request. Our application will have a guard Admin. after defining the guards set their providers. When we use these guards it tells what to use for authentication or validation. Open the Admin.php file in the app/Models folder. Update guard as admin and fillable array with field names.

Open config/auth.php for adding guard. We’ve added one guard: admin and updated their provider’s array.

Step 8: Set Up Controller

Open the LoginController in app/Http/Controllers/Auth and edit as follows:

We set the middleware to restrict access to this controller or its methods. It is important we defined all the different types of guests in the controller. This way, if one type of user is logged in and you try to use another user type to log in, it will redirect you to a predefined authentication page.

Now, define the login for admins:

app/Http/Controllers/Auth/LoginController.php

We have set up a method to return the login page for an admin. We will use the same page for all the user types and only change the URL they get sent to. Saves us a lot of code we could avoid writing.

We also defined the adminLogin the method which checks that the right credentials are supplied. Then we attempt to log a user in with the admin guard. It is important we set this guard when attempting a login so that the Auth facade will check the right table matching credentials. It will also set up our authentication so we can restrict pages based on the type of user who is logged in.

Step 9: Modify RegisterController

Open the RegisterController and edit as follows:

We have set up the middleware the controller will use, just like we did with the LoginController.

Now, let us set up the methods to return the registration pages for the admin:

Now, we can define our methods for creating an admin:

Step 10: Set up authentication pages

Open the resources/views/auth/login.blade.php file and edit as follows:

We are checking if we passed a route parameter to the page when we called it. If we did, we modify the form's action to use the route parameter. We also modified the header of the form so that it shows the type of user based on their login parameter.

Open the resources/views/auth/register.blade.php file and edit as follows:

We replicated what we did for the login page here.

Step 11: Create the pages for authenticated users

Now that we are done setting up the login and register page, let us make the page the admin will see when they are authenticated. Open the terminal and run the following commands to create a new file. Next, we will insert the corresponding code snippets into the files.

Next, insert this code block into the resources/views/admin.blade.php file:

Finally, open the resources/views/home.blade.php file and replace with the following:

Step 12: Set up the routes

Let us define the routes to access all the pages we have created so far. Open the routes/web.php file and replace with the following:

Step 13: Modify RedirectIfAuthenticated.php Middleware

It is important you modify how users are redirected when they are authenticated. Laravel by default redirects all authenticated users to /home. We will get the error below if we do not modify the redirection.

open the app/Http/Controllers/Middleware/RedirectIfAuthenticated.php file and replace with this:

The RedirectIfAuthenticated middleware receives the auth guard as a parameter. This middleware is triggered when we try to visit any page meant for authenticated users.

Step 14: Modify authentication exception handler

Open the handler file app/Exceptions/Handler.php and add the following:

The unauthenticated the method we just added resolves this issue we have. It receives an AuthenticationExpection exception by default which carries that guard information.

Our workaround is to use request->is(). This checks the URL we are trying to access. It can also check the URL pattern if we do not have an absolute URL or if we have a route group.

In our case, we first check if we received a JSON request and handle the exception separately. Then we check if we are trying to access /admin any URL preceded by admin. We redirect the user to the appropriate login page.

This is a good workaround for us, but it means we must know the absolute URL we want to access, or at least have the same prefix for all routes that will be protected by our guard.

Step 15: Run the application

Now that our application is ready, run the following command to get it up:

Most Probably Application URL will be http://localhost:8000.

Remember to visit http://localhost:8000/admin and http://localhost:8000/admin/register.

Conclusion

In this article, we dived deep into Laravel authentication. We defined multiple guards to handle multiple authentications and access control. We also handle redirection for authenticated users and redirection for unauthenticated users.

The source code to the application in this article is available on Github.

Thank you for reading this blog.

--

--

We are sharing Blogs that are related to 🌍 Web and 📱 Mobile Applications issues and examples of Development. We are share blogs related to Laravel, PHP, CodeIgniter, HTML, CSS, Bootstrap, Javascript, jQuery, MySQL, MongoDB, Node.js, Vue.js, Nuxt.js.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Smit Pipaliya

Smit Pipaliya

I am Senior Developer at ServerAvatar Technology.