在我的 Laravel 5.8 项目中,我正在实现一个类似于 Stack Exchange 的信誉系统:例如,用户只有在具有“3 级”信誉时才能回复讨论。
我想在我的 DiscussionPolicy 文件中使用 Laravel 的策略系统来构建权限逻辑:
public function reply(User $user)
{
$result = true;
if ($user->current_level < 3) {
$result = false;
//I want to inject a custom error message here
}
return $result;
}
一切正常,但用户在没有任何解释的情况下得到 403 页面,我想找到一种优雅的方式告诉他们他们无法执行该操作,因为他们没有级别 3。您能否建议一种以某种方式注入(inject)此消息的方法,以在我的自定义 403.blade.php 页面中显示它?我已经能够通过在 session 中闪烁一个变量来做到这一点,但我不认为它很优雅,我想使用类似 MessageBag (Illuminate\Support\MessageBag) 的东西。
LARAVEL 8.x:检查 this answer .
最佳答案
答案在评论中给出,放在这里供引用:
Laravel 通过 deny()
提供此功能。 HandlesAuthorization
中的函数特征。 deny()
函数抛出 UnauthorizedException
但允许您指定消息而不是抛出普通异常。
替换 return false
有了它,您可以发送自定义消息以在异常处理程序中呈现。
例子:
public function reply(User $user)
{
if ($user->current_level < 3) {
$this->deny('Sorry, your level is not high enough to do that!');
// Laravel 6+ requires you to return the deny(), see following line
// return $this->deny('Sorry, your level is not high enough to do that!');
}
return true;
}
关于laravel - Laravel 策略授权的自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56473607/