Laravel 如果使用 gates 授权失败则重定向
Laravel redirect if authorization failed using gates
在我的应用程序中,我使用 gates
来验证登录用户的 authorization
。我希望使用自定义消息将用户重定向到仪表板,而不是显示传统的 403 | This action is unauthorized.
页面。
这是我的代码:
class SomeController extends Controller
{
public function index()
{
# access
if(!$this->authorize('some-role'))
{
session->set('message', 'message');
return redirect()->route(...);
}
...
}
}
这可能吗..?
内部控制器检查的简单方法here:
if (Gate::denies('update-post', $post)) {
// The current user can't update the post...
}
正确的方法。
有 app\Exceptions\Handler.php
有渲染方法,您可以在其中设置 custom exception NotAuthorizedException
(laravel < 5.5):
if($exception instanceof NotAuthorizedException){
return redirect($exception->route());
}
如果 laravel > 5.6,您可以添加以下代码并在 app\Exceptions\Handler.php
中重定向 render
方法:
if ($exception instanceof AuthorizationException)
在我的应用程序中,我使用 gates
来验证登录用户的 authorization
。我希望使用自定义消息将用户重定向到仪表板,而不是显示传统的 403 | This action is unauthorized.
页面。
这是我的代码:
class SomeController extends Controller
{
public function index()
{
# access
if(!$this->authorize('some-role'))
{
session->set('message', 'message');
return redirect()->route(...);
}
...
}
}
这可能吗..?
内部控制器检查的简单方法here:
if (Gate::denies('update-post', $post)) {
// The current user can't update the post...
}
正确的方法。
有 app\Exceptions\Handler.php
有渲染方法,您可以在其中设置 custom exception NotAuthorizedException
(laravel < 5.5):
if($exception instanceof NotAuthorizedException){
return redirect($exception->route());
}
如果 laravel > 5.6,您可以添加以下代码并在 app\Exceptions\Handler.php
中重定向 render
方法:
if ($exception instanceof AuthorizationException)