User Role and Permission(Laravel)
Dec 7, 2020
- 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