Reputation: 1179
I read the official page about validation in laravel http://laravel.com/docs/validation#working-with-error-messages and I followed them. So my code is
$input = Input::all();
$validation = Validator::make($input, Restaurant::$rules);
if ($validation->passes())
{
Restaurant::create($input);
return Redirect::route('users.index');
}
else{
$messages = $validation->messages();
foreach ($messages->all() as $message)
{
echo $message + "</br>";
}
}
I can see the error message but it is just 00
. Is there a better way to know in which form's field the error is and what is the error description?
I already have rules
and I now the input is breaking the rules but I need to read the error message
Upvotes: 1
Views: 17418
Reputation: 6916
You can access errors through the errors()
object, and loop through the all rules' keys.
Something like this:
Route::get('error', function(){
$inputs = array(
'id' => 5,
'parentID' => 'string',
'title' => 'abc',
);
$rules = array(
'id' => 'required|integer',
'parentID' => 'required|integer|min:1',
'title' => 'required|min:5',
);
$validation = Validator::make($inputs, $rules);
if($validation->passes()) {
return 'passed!';
} else {
$errors = $validation->errors(); //here's the magic
$out = '';
foreach($rules as $key => $value) {
if($errors->has($key)) { //checks whether that input has an error.
$out.= '<p>'$key.' field has this error:'.$errors->first($key).'</p>'; //echo out the first error of that input
}
}
return $out;
}
});
Upvotes: 1
Reputation: 28799
$messages = $validation->messages();
foreach ($messages->all('<li>:message</li>') as $message)
{
echo $message;
}
After calling the messages method on a Validator instance, you will receive a MessageBag instance, which has a variety of convenient methods for working with error messages.
According to the MessageBag documentation the function all Get all of the messages for every key in the bag.
Upvotes: 6