Multi guard authentication in laravel 5.8

Here is another interesting topic of guard in laravel we are going to cover in this post. As we all know user authentication can be achieved in jiffy, that is, run php artisan make:auth and you will get controllers, blade views all ready to launch with authentication.

But…but… Here is the catch. Laravel provides default authentication on User model or users table , what if there are two types of users completely different to each other, for example application users and admins ?

One thing we can do is, make a column in users table with name as type and there we define type of user, 1 for admin and 0 for normal user. This method is completely wrong, do not do this ever. Period.

Keep normal users in user table and for admins create another table as admin. Laravel ships a default authentication guard called as web which is applied on User model. For instance go to config/auth.php

'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

What is a guard in laravel authentication?

A guard is a way of supplying the logic that is used to identify authenticated users. Laravel provides different guards like sessions and tokens. For this article, I am just taking session guard which is web by default.

config/auth.php

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ]
],
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ]
],

As you can see, the default authentication guard web is applied on User model.

How to create a guard in laravel ?

As I said earlier, make another table and model for admin users, admin table and Admin model respectively using following commands.

php artisan make:migration create_admins_table

And for Admin model

php artisan make:model Models/Admin

You can copy the database schema of users table to admins table from database/migrations/<timestamp>_create_users_table.php or you can add your custom schema too.

Edit config/auth.php

Add following in guards array:

'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

And in providers array:

'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],

Create middlewares for normal users and admin users routes

What is middleware in laravel ?

A middleware is a piece of code which is executed before a particular route hits a controller method. Basically middlewares are used for authentication purposes so that protected routes/endpoints should not be hit by any outside user or application, once a request is authenticated its control is passed next to the controller method.

Now create 2 middlewares for routes which belong to normal users and admin users respectively.

php artisan make:middleware AuthUsers

php artisan make:middleware AuthAdmins

Above commands will create 2 files in app/Http/Middleware directory

AuthUsers middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Illuminate\Support\Facades\Session;

class AdminUsers
{
    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request $request
    * @param  \Closure $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        if (false == Auth::check()) {
            return redirect()->route('view.login); //redirect User to login page
        }

        return $next($request);
    }
}

AuthAdmins middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Illuminate\Support\Facades\Session;

class AdminAuth
{
    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request $request
    * @param  \Closure $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        if (false == Auth::guard('admin')->check()) {
            return redirect()->route('view.login.admin');
        }

        return $next($request);
    }
}

Here in this middleware, I am telling laravel to use admin guard on this middleware and check() if admin is logged in otherwise redirect the request to login route and then route will load login view for the admin.

Register middlewares in Kernel.php

Now it’s time to register these two middlewares in Kernel.php, here you need to be careful as there are 2 Kernel.php in laravel one is at app/Console directory and other one is at app/Http directory. We need to take the later one which is app/Http/Kernel.php for middleware registrations.

Add the following 2 lines in protected $routedMiddleware array

protected $routeMiddleware = [
        'auth.user => \App\Http\Middleware\AuthUsers::class,
        'auth.admin' => \App\Http\Middleware\AuthAdmins::class,
];

Apply middlewares on their respective routes in web.php

For authenticated users:

Route::group(['middleware' => ['auth.user]], function () {
    // login protected routes.
});

For authenticated admin users:

Route::group(['middleware' => ['auth.admin]], function () {
    // login protected routes.
});

Conclusion

So friends, it was all about guards and middlewares in laravel. I hope you enjoyed this tutorial and helped you. Please share this post with your friends on facebook, twitter as a good gesture for me to keep posting interesting topics.

Thank You !

Source: Tumblr