Set-up role based access control in Laravel

Set-up role based access control in Laravel

Many a time in a web application you will need to protect certain resources from being accessed by all of your users. While an authentication system ensures that only authorized users are able to access your application but implementing a certain role-based access control is sometimes necessary. Let me show you how you can implement role based access control in Laravel.

We will not be using any external packages and just use Laravel Middlewares to implement this. We will be implementing access control for 3 roles namely Admin, Agent, and Customer for the User model provided by Laravel.

Set up migrations:

  • Add a new role column to our existing user migration:

     
  • Run the migrations to generate the tables:

    Note: If you have already generated the tables before, you may need to run php artisan migrate:refresh but be aware that this command will reset all your tables! and then re-run all your migrations.

 

Customize the registration form:

  • Generate the authentication scaffolding which comes bundled with Laravel.
  • Now that we have added the role column to our user model we also need to add the input for the roles in our view so add the select tag input to resources/views/auth/register.blade.php‘s registration form.

    Set-up_role_based_access_control_in_Laravel-registration_form
    The registration form

 

Customize User Model and Register Controller:

  • Add the role column to fillable attribute on the User Model so that we can make use of the create() method in Register Controller.
  • Now customize RegisterController.php which is located in app/Http/Controllers/Auth directory to include our role input when creating a new user.
    • Add a validation rule for the role field:
    • Add role field to the create() method:

       

Now you should be able to register users with different roles so create at least one user per each role and we will move on to implementing the access control logic.

Set-up middlewares:

Middleware provide a convenient mechanism for filtering HTTP requests entering our application. For example, Laravel includes an auth middleware that verifies the user of your application is authenticated.

  • We will create middlewares for each of our roles.
  • Add the following code to each of the middleware which is located in app/Http/Middleware directory:
    • Admin.php:
    • Agent.php:
    • Customer.php:
  • Now let’s register our middleware with Laravel by adding the middleware classes to $routeMiddleware property located in app/Http/Kernel.php:

 

Now you can apply these middlewares to routes or to the controller itself:

  • web.php:
  • Or you can specify a middleware in a controller’s constructor, like this:

 

That’s it, we have successfully implemented role based access control in Laravel! and you can adapt this method for as many or as few of the roles you might need.

The example project used in this tutorial can be found in my GitHub repository.

If you liked this tutorial then you might be interested in my other tutorials in the Laravel section and be sure to leave any comments or ask any questions you might have in the comment section below!

23
Leave a Reply

avatar
12 Comment threads
11 Thread replies
4 Followers
 
Most reacted comment
Hottest comment thread
13 Comment authors
mohiminulbilacristian dumitriusapneshnaikCristian Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Amratha Tendulkar
Guest
Amratha Tendulkar

👌

Harry McKinney
Guest
Harry McKinney

Wow, this is very cool!

Devlim
Guest
Devlim

This work for page level and route level access control. Is there any guide for page element access control? Such as hide delete button for non-admin, disabled edit capability for certain form field access control?

Žymantas
Guest

Nice one 😉

Nikolay Traykov
Guest
Nikolay Traykov

How do you know if the Admin is above the Customer in the hierarchy and that everything that applies to the Customer applies to the Admin as well?

Udaiyar
Guest
Udaiyar

Nice one.

sagagt505
Guest
sagagt505

I have a question? if I want to redirect to different route for different type of user what should i do next? I am newbie for this.

himanshu
Guest
himanshu

this error is irritating me, please help after login —– Trying to get property of non-object D:\xampp\htdocs\authrole\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php protected function addCookieToResponse($request, $response) { $config = config(‘session’); $response->headers->setCookie( new Cookie( ‘XSRF-TOKEN’, $request->session()->token(), $this->availableAt(60 * $config[‘lifetime’]), $config[‘path’], $config[‘domain’], $config[‘secure’], false, false, $config[‘same_site’] ?? null ) ); return $response; }

cristian dumitriu
Guest
cristian dumitriu

I found the problem. Check the handle function in the middleware . I have copied the function wrong. Check them and will be solved.

cristian dumitriu
Guest
cristian dumitriu

I have the same error – did you figure it out?

Kajal
Guest
Kajal

Very nice, thanks for this tutorial 🙂

Cristian
Guest
Cristian

Thank you Naik. I was looking for this.

bila
Guest
bila

Route::get(‘/home’, function(){
echo “Hello Admin”;
})->middleware(‘auth’,’admin’,
‘auth’,’client’
);
how to implement this

mohiminul
Guest
mohiminul

after login—redirect to home in this proces
is it possible to redirect admin panel/agent or/customer panel after login