Laravel Create a custom middleware class that checks the user’s role

·

Laravel 7.2 routing with route group auth guard check with prefix

Hell to all, welcome to therichpost.com. In this post, I will tell you, how to Create a Laravel custom middleware class that checks the user’s role?

Laravel now a days top php mvc framework. I am also learning laravel.

Here we start the code for Laravel custom middleware class that checks the user’s role:

1. First, we will create middleware with artisan command:

php artisan make:middleware Checkrole

2. Above command creates a file called Checkrole.php within the app/Http/Middleware directory that looks like and I have modified code little bit as my requirement for check user role:

<?php

namespace App\Http\Middleware;

use Closure;

class Checkrole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // hasRole being a function defined on your User model that checks
        // a user's assigned role(s).
        if (auth()->check() && auth()->user()->hasRole('BETA Tester')) {
            return $next($request);
        }

        abort(401, 'You are not allowed to access this page');
    }
}

 3. You then need to add the Checkrole Middleware to your app/Http/Kernel.php file:

protected $routeMiddleware = [
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    'admin' => 'App\Http\Middleware\Checkrole', // this line right here
];

 4. You can use the Checkrole Middleware to a route. (Within your routes.php file):

get('protected', ['middleware' => ['auth', 'checkuser'], function() {
    return "this page requires that you be logged in and an Admin";
}]);

 This is it, if you have any query related to this post, then please do comment or email me.

 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.