Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cristian9509's avatar

How to deal with roles and permissions

I have setup my database and have the tables required for role based access control. I have, users, user_role, roles, role_permission, permissions. I understand how it should work and how to create the specific roles and permissions.

What I don't understand is where do I store the roles/permissions that I need to check on the pages/routes/middleware in order to confirm that what permissions are store in the database for a specific users are the ones that grant them permission to access a resource.

Would I need to do something like this for example in a route? Or use route groups to group specific resources?

Admin page: roles required: admin permissions: _edit_users, _create_users, _delete_users, etc

If User has role admin OR if User has permissions: grant them access?

0 likes
2 replies
starbolt's avatar

Hi Cristian

This is the way I've been doing that...

First you create a middleware. Use php artisan like so:

php artisan make:middleware name

Then you will find the middleware file located here: app/Http/Middleware

Edit the middleware file and place the logic needed (role and other verifications)

You can find an example here: http://laravel.com/docs/master/middleware#defining-middleware

Then, you need to register it on the kernel file: app/Http/Kernel.php.

Here is an example from Laravel documentation:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];

The array key is name you are going to give to the middleware (and to be used on the routes) and the value references the class on the middleware file you created earlier.

You can then use the middleware on your routes file and group them as you like.

Route::get('admin/profile', ['middleware' => 'auth', function () {
        //
}]);
cristian9509's avatar

Thank you. So, if I understand correctly, every role/permission check should be done in the middleware layers. Like this:

  • check if user is Authenticated
  • check for Role of specific resource
  • check for Permissions if Roles don't provide the necessary permissions
  • check for User Status (active/deactivated)
  • any other layer

And this should make the "onion" that Jeff describes in a video, right?

And if one of my database role is named _basic_user, this is the name that I need to check in the middleware in order to grant permission?

Please or to participate in this conversation.