Reputation: 827
I've just started to test out Laravel. I'm using a form with some fields and trying to validate the inputs using Laravel's built-in validator class.
$input = Input::all();
$rules = array(
'fname' => 'required|max:100',
'lname' => 'required|max:100',
'email' => 'required|email',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()){
return Redirect::to('inputform')
->with('input_errors', $validation->errors);
}
Everything goes well, and the validation check works. When validation fails, I put the errors in a session variable called input_errors
and pass it to the view. My problem is that I can't seem to display the errors. I tried a foreach
loop using the blade templating engine
as given below:
@foreach (Session::get('input_errors') as $message)
{{ What Should I put here? }}
@endforeach
How can I display the errors that are being returned as an array. I tried referencing it as $message[0][0]
but it didn't work.
Thanks.
EDIT: Sorry, forgot to mention that I'm using Laravel 3
Upvotes: 1
Views: 6879
Reputation: 33058
The correct syntax for getting the errors is...
$messages= $validation->messages();
That alone, unfortunately, is not going to return you the messages. It's going to return a MessageBag
instance. This allows you to pull out any specific messages you want or all.
If you want to get all the messages, now you can do do...
$errors = $messages->all();
That will return an array you could loop through in your view to display errors. There are also methods for getting errors on a specific field such as...
$firstNameError = $messages->first('fname');
or
$firstNameErrors = $messages->get('fname');
I also suggest when sending error messages to the view, to use...
->with_errors($validation);
That will flash the errors to session and automatically assume you are sending them as an $errors
variable. Then you may display the errors in your view with.
{{ $errors->first('fname') }} // Blade approach
<?php echo $errors->first('email'); ?> // Non-blade approach
This way, you don't have to add logic to your views trying to determine if the variable exists before you should try and echo it.
http://four.laravel.com/docs/validation
Upvotes: 4