User Role and Permission(Laravel)

  1. Add new field in User table:

app/user.php

2. Crete Model and Table:

php artisan make:model Role -m
$table->string('role_name')->nullable();
$table->longText('permission')->nullable();

3. Create Relationship with user table and roles table.

App/User.php

public function roles()
{
return $this->belongsTo(Role::class);
}

database/migrations/2014_10_12_000000_create_users_table.php

$table->integer('role')->unsigned()->nullable();
$table->foreign('role')->references('id')->on('roles')->onDelete('cascade');

App/Role.php

public function users()
{
return $this->hasMany(User::class);
}

4. App/Providers/AuthServiceProvider.php

Gate::before(function ($user) {
if ($user->id == "1") {
return true;
}
});
Gate::define('add_category', function($user) {

$role = \App\Role::where('id', $user->role)->first();
foreach(json_decode($role->permission,true) as $permission)
{
if($permission == '1')
{
return true;
}
}

});

5. Give access by:

@canany(['add_category','edit_category','delete_category'])
you can edit update delete category
@endcanany
@can('isAdmin')You have Admin Access@elsecan('isManager')<div class="btn btn-primary btn-lg">You have Manager Access</div>@else

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Disputes Among Contractors

disputes among contractors

PC Free Emoji Tools : Emoji Burger (2022)

Kill the temp variables!

Core Differences Between MVP, MLP and MMP/MSP — Which one to prefer?

My experience at JENGA School sepa program during sprint 3

Combining Roles in Scrum: Pros and Cons!

Why Google Abseil Is Cooler Than It Looks and What It Can Teach Us About C++ Libraries in General?

4 Live Streaming Techniques for your CV Project

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Safaetul Ahasan

Safaetul Ahasan

Software Engineer

More from Medium

How To Test Mail and Database Notifications in Laravel 8

Simple roles and permissions package for Laravel

How to add custom properties to Laravel Activities Log

How to Install and Configure your first Laravel Application