When using $this->validate()
if your validation fails you'll be returned back to the previous URL with all errors and error messages for the fields that didn't pass your validation rules in the session, so you shouldn't need to additionally flash anything to the session. As mentioned in the docs:
So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session.
What you can do instead is check for the presence of error messages in your view and output your desired text. You can access errors with the $errors
variable in your view, as mentioned in the docs:
Again, notice that we did not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will check for errors in the session data, and automatically bind them to the view if they are available. The $errors variable will be an instance of Illuminate\Support\MessageBag. For more information on working with this object, check out its documentation.
For example, in your view you could do the following:
@if (count($errors) > 0)
<div class="alert alert-danger">
Validation Fails
</div>
@endif
If you really have to flash data to the session you could try checking for the $errors
variable in your controller method for loading the view then putting data in the session based on its value. Never tried this so you may need to test it out.
public function index()
{
if(count($errors) > 0) {
session()->put('foo', 'bar');
}
return view('my-form');
}
As a side point also consider that you don't have to use $this->validate()
you can instead use Form Request Validation. Additionally as a general advice it may be worth reviewing the documentation for how validation works: https://laravel.com/docs/5.2/validation#introduction.
Hope that helps!