29.07.2016 Views

laravel-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Validation 372<br />

Displaying The Validation Errors<br />

So, what if the incoming request parameters do not pass the given validation rules? As mentioned<br />

previously, Laravel will automatically redirect the user back to their previous location. In addition,<br />

all of the validation errors will automatically be flashed to the session.<br />

Again, notice that we did not have to explicitly bind the error messages to the view in our GET route.<br />

This is because Laravel will always check for errors in the session data, and automatically bind them<br />

to the view if they are available. So, it is important to note that an $errors variable will always<br />

be available in all of your views on every request, allowing you to conveniently assume the<br />

$errors variable is always defined and can be safely used. The $errors variable will be an instance<br />

of Illuminate\Support\MessageBag. For more information on working with this object, check out<br />

its documentation.<br />

So, in our example, the user will be redirected to our controller’s create method when validation<br />

fails, allowing us to display the error messages in the view:<br />

.<br />

1 <br />

2<br />

3 Create Post<br />

4<br />

5 @if (count($errors) > 0)<br />

6 <br />

7 <br />

8 @foreach ($errors->all() as $error)<br />

9 {{ $error }}<br />

10 @endforeach<br />

11 <br />

12 <br />

13 @endif<br />

14<br />

15 <br />

Customizing The Flashed Error Format<br />

If you wish to customize the format of the validation errors that are flashed to the session when<br />

validation fails, override the formatValidationErrors on your base controller. Don’t forget to<br />

import the Illuminate\Contracts\Validation\Validator class at the top of the file:<br />

.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!