I work on a Content Management System 'CMS', and I use role & permission to make access to resources more specific. "With Spatie Laravel Permission Package"
I wrote this function in the main controller class
// Check Ability
public function checkUserAbility($real_permission, $optional_permissions = [], $operator = '||')
{
$_is_access = true;
if (Auth::user()->hasPermissionTo($real_permission)) {
if (!empty($optional_permissions)) {
foreach ($optional_permissions as $optional_permission) {
if ($operator == '||') {
$_is_access |= Auth::user()->hasPermissionTo($optional_permission);
} else if ($operator == '&&') {
$_is_access &= Auth::user()->hasPermissionTo($optional_permission);
}
}
return $_is_access ? true : App::abort(403);
} else {
return true;
}
} else {
return App::abort(403);
}
}
I use this function normally in the controller function to check the ability to access the resources
public function delete(Super $super)
{
// Check Ability
$this->checkUserAbility('Delete-Super');
if (auth('super')->user()->email == $super->email)
return response()->json([
'icon' => 'error',
'title' => 'Failed !',
'text' => 'Failed to delete super',
], Response::HTTP_BAD_REQUEST);
if ($super->delete()) {
return response()->json([
'icon' => 'success',
'title' => 'Deleted',
'text' => 'Super deleted successfully',
], Response::HTTP_OK);
} else {
return response()->json([
'icon' => 'error',
'title' => 'Failed !',
'text' => 'Failed to delete super',
], Response::HTTP_BAD_REQUEST);
}
}
Another example with the index controller function
public function index()
{
// Check Ability
$this->checkUserAbility('Read-Super', ['Update-Super', 'Delete-Super', 'Ban-Super', 'Follow-Up-Super'], '||');
if (auth('super')->user()->email == 'az54546@gmail.com') {
$supers = Super::all();
} else {
$supers = Super::where('email', '!=', 'az54546@gmail.com')->get();
}
return response()->view('back-end.supers.supers.index', [
'supers' => $supers,
]);
}
Laravel blade view enter image description here
When I try to access this resource the access will be forbidden and load the Laravel 403 Access Forbidden. The point is how to load another view when this access is forbidden.
Publish Laravel's default error page templates using the vendor:publish
Artisan command.
php artisan vendor:publish --tag=laravel-errors
The files of the error in the following directory
resources/views/errors
Once the templates have been published, you may customize them to your liking:
Official document link : Custom HTTP Error Pages