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

peterpan26's avatar

Customize user roles in laravel 8

Hello, i've disabled new registrations on my project with the following code: Auth::routes(['register' => false]); Now i need to setup user roles, i know if i want a new role i need to add it in kernel and then in the web.php setup the routes, and i also created middleware. but it's not working as intended, because for example lets say "X" page is for admin only, and i want to make page "X" available to admin and superadmin, for example page "y" : available for superadmin only and not for admin.~ how should i do this?

0 likes
10 replies
peterpan26's avatar

I added on the user model the HasRoles, and created a role with a permission with spatie, but i see that i already have on table of users and a column of Role_as, how should i proceed now ?

Sinnbeck's avatar

@peterpan26 So you have tried implementing it yourself I assume? laravel does not come with roles or permissions out of the box

peterpan26's avatar

i've used the artisan command to create the role and permission, then i've put in user model i had before the hasrole. i set the permission to the role to be able to "create formularios" wich means create forms, and i have a working form in my project called formulario

Sinnbeck's avatar

@peterpan26 So all good ? Now you just need to restict some route with it.

Route::get('foo', [SomeController::class, 'index'])->middleware(['can:create formularios']);
peterpan26's avatar

i've done it now (setup the routes as you told), how can i assign a role to a user? for example this role i have how do i assign it to the current users table i have to the users i want?

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@peterpan26 You dont add it on the users table. The package has its own table for these things. I recommend adding permissions to roles, and then roles to users, but you can add a permission directly to a user

https://spatie.be/docs/laravel-permission/v5/basic-usage/direct-permissions

$user->givePermissionTo('create formularios');

Or as I said the better way

$role = Role::create(['name' => 'admin']);
$role->givePermissionTo('create formularios');
$user->assignRole('admin');
Sinnbeck's avatar

@peterpan26 Where ever you assign roles ? I have created a page where I can assign roles and permissions to each user. But I dont know where it makes sense in your app.

peterpan26's avatar

in the registered users dashboard, i could create an edit role button for admin only .~ thanks my question is solved thanks @sinnbeck

Please or to participate in this conversation.