Last active
February 3, 2020 15:55
-
-
Save me7media/b14c5a9a68ea80b3a961de16b1a9a167 to your computer and use it in GitHub Desktop.
Laravel User Roles Permissions through Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Kernel | |
'permission' => \App\Http\Middleware\Permissions::class, | |
//Middleware\Permissions | |
public function handle($request, Closure $next, $permission = '') | |
{ | |
if (!$request->user() || !$request->user()->hasPermission($permission)) { | |
return redirect('/'); | |
} | |
return $next($request); | |
} | |
//User | |
public function role() | |
{ | |
return $this->belongsTo(Role::class, 'role_id'); | |
} | |
public function hasPermission($permission = '') | |
{ | |
$perms = explode('.', $permission) ?? []; | |
$perms[0] = isset($perms[0]) ? $perms[0] : request()->segment(2); | |
$perms[1] = isset($perms[1]) ? $perms[1] : 'access'; | |
return optional(optional(optional(optional($this->role)->permission)->where('value', Str::plural($perms[0])))->first())->{$perms[1]}; | |
} | |
//Role | |
public function permission() | |
{ | |
return $this->hasMany(Permission::class); | |
} | |
//Permission | |
protected $fillable = ['name', 'value', 'role_id', 'access', 'view', 'create', 'edit', 'delete']; | |
USE | |
Route::resource('permissions', 'Admin\PermissionsController')->middleware('permission:permissions.access'); | |
OR | |
Route::post('post_destroy', ['middleware' => ['auth', 'permission:post.delete'], 'uses' => 'Admin\PostController@destroy', 'as' => 'post.destroy']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment