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
相关产品推荐
相关产品推荐

