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 authorised 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.

 

Customise 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 customise RegisterController.php which is 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. We’ll 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 respective middlewares which are located in app/Http/Middleware folder:
    • Admin.php:
    • Agent.php:
    • Customer.php:
  • Now let’s register our middleware with Laravel. Add 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:

 

Redirect User After Log-in:

If you use Laravel’s default login setup, you may want to redirect the user to his role specific page after he logs in. and you can do that by overriding the redirectTo() method in your LoginController.php. Make sure you remove the $redirectTo property from your LoginController.php.

Add this to your LoginController.php:

 

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!

34
Leave a Reply

avatar
18 Comment threads
16 Thread replies
10 Followers
 
Most reacted comment
Hottest comment thread
19 Comment authors
kiranSapnesh NaikVincent LibronSimonAnon 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 have the same error – did you figure it out?

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.

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

Eren Christian
Guest
Eren Christian

have a same question

Haidar
Guest
Haidar

in login page if user selected admin how to redirect user to admin page

Eren Christian
Guest
Eren Christian

hi
what to write in protected $redirectTo = ‘/login/checkrole’; in LoginController.php

Anon
Guest
Anon

Thank you so much, very helpful!

Simon
Guest

Really great stuff! work really well

Vincent Libron
Guest
Vincent Libron

say the role field is in another table like
user_type(…){
$table->increment(‘id’);
$table->string(‘type_name’);
}
then the 3 user type is defined in the dbseeder with 1 – admin 2- agent 3-customer
and the user_type table is referenced in the users table.

kiran
Guest
kiran

i have used this when i register it goes directly on auth dashbaord which laravel default and when i used LoginController changed then redirect is not working