Laravel 5.4 FormRequest forbiddenResponse() 方法已被 failedAuthorization() 取代

Laravel 5.4 FormRequest forbiddenResponse() method has been replaced by failedAuthorization()

如标题所述,我注意到 forbiddenResponse() 方法已从 Laravel 5.4 中的 FormRequest 中删除。

此方法已被 failedAuthorization() 方法取代,该方法现在会触发 AuthorizationException

这给我带来了麻烦,因为我需要从表单请求进行重定向,但现在看来这不可能了。

有人有这样的解决方案吗?

转到 App\Exceptions\Handler 并将其添加到 render 方法中:

if ($exception instanceof AuthorizationException) {
    // Do what you want here, Response, Redirect...
}

抱歉耽搁了,自从我上次留言后我就当父亲了 ;)

这是自从你给我小费后我所做的。

我创建了我的 formRequests 扩展的 BaseRequest class。在其中,我重写了 failedAuthorization 方法:

protected function failedAuthorization()  
{
    $exception = new AuthorizationException('This action is unauthorized.');
    $exception->error_message = $this->error_message;
    $exception->redirect = $this->getRedirectUrl();
    $exception->dontFlash = $this->dontFlash;           
    throw $exception;
}

App\Exceptions\Handlerclass中,我在render方法中添加了如下处理:

if ($exception instanceof AuthorizationException) {  
    // ajax or api call  
    if ($request->expectsJson()) {
        // treatment
    }

    // we notify the current user with a modal
    if($exception->error_message) Modal::alert($exception->error_message, 'error');

    if ($exception->redirect){
        return redirect()->to($exception->redirect)->withInput(request()->except($exception->dontFlash));
    } else {
        return redirect()->back()->withInput(request()->except($exception->dontFlash));
    }
}  

通过这个过程,我对可定制的 formRequest 使用有了满意的处理。但是我还是觉得有点乱,不是很干净。如果您或其他人有更好的实现方式,我很乐意与您讨论。