User Role and Permission

  1. Add new field in User table:

app/user.php

Image for post
Image for post
Image for post
Image for post

2. Crete Model and Table:

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

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

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