How to handle different types of user role in laravel without any packages?

Author - Ramesh Vaniya

What is Laravel?

Laravel is free open source web development framework. It is based on model view controller (MVC) pattern and based on Symfony.

What is Middleware?

Laravel Middleware is the easy approach of verifying HTTP requests before they are passed to the controller.

There are lots of packages available in Laravel to restrict role-based user permission. But if you don’t want to use package and complexity then create custom middleware and we can handle any role easily. From below some points, we can achieve the goal as a result.

> Create custom middleware

> Modify handle method for middleware and handle user roles

> Use of custom middleware

> Create error pages

Create custom middleware

From below command it will create new file checkRole middleware inside your app/Http/Middleware folder

php artisan make:middleware CheckRole

We must register middleware in app/Http/Kernel.php class otherwise it will give error that our middleware class not found.

protected $routeMiddleware = [
        'checkRole' => \App\Http\Middleware\CheckRole::class,
 ];

Modify handle method of middleware and handle user role

First of all let’s start code for handle user role in App\Http\Middleware\CheckRole.php

Default handle method structure:

public function handle($request, Closure $next)
{
	// place here your code
}

In Above code , handle() method have by default two argument first is Request class object and second is closure class object.

Besides that, we need to add third argument for check user role.

public function handle($request, Closure $next,$role='')
{

        $userRole = $request->user();

        if($userRole && $userRole->count() > 0)
        {
            $userRole = $userRole->role;
            $checkRole = 0;
            if($userRole == $role && $role =='admin')
            {
                $checkRole = 1;
            }
            elseif($userRole == $role && $role == 'manager')
            {
                $checkRole = 1;
            }
            elseif($userRole == $role && $role == 'employee')
            {
                $checkRole = 1;
            }
            
            if($checkRole == 1)
                return $next($request);
            else
               return abort(401);
        }
        else
        {
            return redirect('login');
        }
    }

In above handle() method get user by $request->user() method

If user is logged in then check user role otherwise redirect to login page.

We have three roles :-  1. admin, 2. manage, 3. employee.

First if($userRole==$role && $role==’admin’) condition check admin user role

If this condition will be true then after $checkRole variable value will change and store 1.

Second if($userRole==$role && $role==’manager’) condition check mange user role

If this condition will become true than after $checkRole variable value will change and store 1.

Third if($userRole==$role && $role==’employee’) condition check employee user role

If this condition will become true than after $checkRole variable value will change and store 1.

For $userRole==$role check current logged in user and current client request with pass role.

For $role==’employee’ check current client request with employee role.

When $checkRole==1 condition is true then your request will valid otherwise restricted request.

When Laravel is handling a request it runs all the applicable middleware in the stack. It can be set to run before or after the route and controller method.

It $next($request)  is anonymous function it will check all the application middleware in the stack.
abort(403) function for redirect to 403 error page.

Use of custom middleware

We can handle middleware with many ways like:

In routes/web.php make middleware group

Route::group(['middleware' => ['auth','custom-middleware-name']], function () {
	//list of middleware	
})

We can also assign middleware on a single specific route.

Route::get('dashboard','Dashboard@index')->middleware('custom-middleware-name');

We can define middleware in our controller of the constructor.

public function __construct()
{
	// for whole controller methods are restricted
	$this->middleware('custom-middleware-name:role-name');
	// or 
	
	//for some methods are restricted
	$this->middleware('custom-middleware-name:role-name', ['only' => ['index', 'show']]);
}

Create Error Pages

When we have added middleware and restrict user then it’s required to show error and restricted pages so we can generate error pages by below artisan command.

php artisan vendor:publish --tag=laravel-errors

These are error pages we do not need to define in our route file because laravel automatically handles it.

Above command run, after you will see create new errors directory in your resources/views

Error pages will be like below :-

  401 – You are not authorized to access this page.

  403 – You are forbidden from accessing this page.

  404 – The page you are looking for could not be found.

  419 – Your session has expired. Please refresh and try again.

  429 – You are making too many requests to our servers.

  500 – Something went wrong on our servers.

  503 – We are doing some maintenance. Please check back soon.

From above all simple steps you can easily handle multiple roles like that way without installing laravel package.

Finally, hope this blog will help to all. If you have any query or suggestion please comment below. And even more you can get the source code from GitHub.

laravel-user-role-base-permision-without-any-package

Free SEO Checker |
Test your website for free with OnAirSEO.com

Get Your SEO report!

Don’t miss the next post!

Loading

Related Posts