Code will be execute or stop if validation fail in

2019-09-08 15:03发布

问题:

I wanted to know that what will be happen if validation fail in laravel, means that the rest of code will be execute or not. I have following code in store method

$this->validate($request, [
    'name' => 'required|min:3',
    'email' => 'required|email',
    'message' => 'required',
]);

return response()->json([
    'success' => 'Your email has been sent successfully.'
]); 

I have checked with $validator->fails()) but it does not return the error message which i added in the if statement.

if($validator->fails()) {
    return response()->json([
        'error' => 'There are some errors.'
    ]); 
}else{
    return response()->json([
        'success' => 'Your email has been sent successfully.'
    ]); 
}

Can anyone guide me about my question, i would like to appreciate. Thank You

回答1:

No an exception will be thrown in your case upon validation fails. According to laravel official doc:

The validate method accepts an incoming HTTP request and a set of validation rules. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.

If you do not want to use the ValidatesRequests trait's validate method, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator

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...
    }
}


回答2:

if($validator->fails())
    return Redirect::back()->withInput()->withErrors($validator);

then the client side:

<ul class="errors">
@foreach($errors->all() as $message)
  <li>{{ $message }}</li>
@endforeach
</ul>