I have set up a controller with some validation.
public function attemptLogin()
{
$rules = array(
'email'=>'required|email',
'password'=>'required'
);
$validator = Validator::make(Input::all() , $rules);
if($validator->fails()){
return Redirect::to('login')->withErrors($validator);
};
}
If I output the messages directly in the controller
$messages = $validator->messages();
print_R($messages->all());
I get the validation errors - however if I redirect:
return Redirect::to('login')->withErrors($validator);
The $errors
array available in the view is always coming up empty.
From laravel four documentation
Note that when validation fails, we pass the Validator instance to the Redirect using the
withErrors
method. This method will flash the error messages to the session so that they are available on the next request.
Variable $errors
it's not an array.
The
$errors
variable will be an instance ofMessageBag
.
For some reason I don't really like @seamlss idea.
You can use this instead.
@if(Session::has('errors'))
<? $errors = Session::get('errors'); ?>
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
<ul>
<li id="form-errors" >
<h3> {{ $errors->first('email') }}</h3>
</li>
</ul>
</div>
@endif
I've used some bootstrap
components, don't get confused, the only thing you need is the lines with the curly braces and the magical @ sign.
From laravel docs error-messages-and-views
So, it is important to note that an $errors variable will always be available in all of your views, on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used.
You can also check this
@if( $errors->has('email') )
<div class="control-group error">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" id="email" placeholder="Email" name="email">
<span class="help-inline">{{ $errors->first('email') }}</span>
</div>
</div>
@endif
I've had success redirecting using ->withErrors($validation)
And then in the view checking the condition @if( $errors->count() > 0 )
...
@if( $errors->count() > 0 )
<p>The following errors have occurred:</p>
<ul id="form-errors">
{{ $errors->first('username', '<li>:message</li>') }}
{{ $errors->first('password', '<li>:message</li>') }}
{{ $errors->first('password_confirmation', '<li>:message</li>') }}
</ul>
@endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With