how to do Role Base Access in Laravel?

81 Views Asked by At

I am new in Laravel How to do in laravel role with the following table

$table->id();
            $table->string('name');
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('role');
    $table->boolean('active');
            $table->rememberToken();
            $table->timestamps();

If user activity and the role is “admin”, should get access to Admin Dashboard page, else if a user is active and the role is “manager” should get access to the manager Dashboard page, if-else user is active and role “DEO”/data entry operator should get entry form else to redirect to the login page with error? Should we write in page.blad.php or in controller functions?

1

There are 1 best solutions below

2
AbdulKarim On BEST ANSWER

The easiest way is to apply user roles is by using this famous spatie/laravel-permission package

This package allows you to manage user permissions and roles in a database.

Once installed you can do stuff like this:

// Adding permissions to a user
$user->givePermissionTo('edit articles');

// Adding permissions via a role
$user->assignRole('writer');

$role->givePermissionTo('edit articles');

Because all permissions will be registered on Laravel's gate, you can check if a user has a permission with Laravel's default can function:

$user->can('edit articles');

Get started