You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中使用can路由授权时,如何替换异常抛出为页面重定向?

Laravel路由can限制未授权时替换异常为页面重定向的方案

默认情况下,在Laravel中使用can路由限制时,若用户未获授权会抛出异常。我希望将异常抛出替换为页面重定向。

web.php路由代码如下:

Route::group(['middleware' => 'auth'], function(){
    Route::get('/users', [userController::class, 'index'])->can('view', 'user');
});

异常由response.php中的authorize方法抛出:

public function authorize()
{
    if ($this->denied()) {
        throw (new AuthorizationException($this->message(), $this->code()))
                    ->setResponse($this);
    }

    return $this;
}

我尝试修改该方法进行重定向,但未生效:

public function authorize()
{
    if ($this->denied()) {
        return redirect('/');
    }

    return $this;
}

UserPolicy.php代码如下:

public function view(User $user)
{
    return $user->hasPermission('user-view');
}

请问是否可以将异常抛出替换为重定向,还是必须在控制器中检查并处理重定向?

内容的提问来源于stack exchange,提问作者mmdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:55:28