我在一个内容管理系统'CMS'上工作,我使用角色和权限来更具体地访问资源。“With Spatie Laravel Permission Package“
我在主控制器类中编写了这个函数
// 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);
}
}
我通常在控制器函数中使用这个函数来检查访问资源的能力
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);
}
}
另一个具有索引控制器功能的示例
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
当我试图访问这个资源时,访问将被禁止,并加载Laravel 403 Access Forbidden。关键是当这种访问被禁止时如何加载另一个视图。
1条答案
按热度按时间lrpiutwd1#
使用
vendor:publish
Artisan命令发布Laravel的默认错误页面模板。以下目录中的错误文件
模板发布后,您可以根据自己的喜好进行自定义:
官方文件链接:自定义HTTP错误页