Laravel 5 custom validation redirection

馋奶兔 提交于 2019-11-30 09:44:56

Found a solutions. All I need to do is to override the initial response from

FormRequest.php

like such and it works like a charm.

public function response(array $errors)
{
    // Optionally, send a custom response on authorize failure 
    // (default is to just redirect to initial page with errors)
    // 
    // Can return a response, a view, a redirect, or whatever else

    if ($this->ajax() || $this->wantsJson())
    {
        return new JsonResponse($errors, 422);
    }
    return $this->redirector->to('login')
         ->withInput($this->except($this->dontFlash))
         ->withErrors($errors, $this->errorBag);
}
dokko

if you want to redirect to a specific url, then use protected $redirect

class LoginRequest extends Request
{
    protected $redirect = "/login#form1";

    // ...
}

or if you want to redirect to a named route, then use $redirectRoute

class LoginRequest extends Request
{
    protected $redirectRoute = "session.login";

    // ...
}

If you are using the validate() method on the Controller

$this->validate($request, $rules);

then you can overwrite the buildFailedValidationResponse from the ValidatesRequests trait present on the base Controller you extend.

Something along this line:

protected function buildFailedValidationResponse(Request $request, array $errors)
{
    if ($request->expectsJson()) {
        return new JsonResponse($errors, 422);
    }

    return redirect()->route('login');
}

If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance: Refer to Laravel Validation

 public function store(Request $request)
   {
    $validator = Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect('post/create')
                    ->withErrors($validator)
                    ->withInput();
    }

    // Store the blog post...
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!