I'm upgrading from Laravel 3 to Laravel 4. My app has some AJAX-only forms that are rendered client-side (i.e. there are no server-side views). Therefore, instead of passing validation errors to views with the withErrors() method, I've been returning the validation error objects to the client as JSON structures.
In Laravel 3, I had this:
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
{
return json_encode($validation->errors);
}
//else handle task
But in Laravel 4, the error messages are protected:
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
{
var_dump($validation->messages());
return json_encode($validation->messages());
}
//else handle task
var_dump($validation->messages()) returns:
object(Illuminate\Support\MessageBag)[333]
protected 'messages' =>
array (size=1)
'delete_confirm_password' =>
array (size=1)
0 => string 'The delete confirm password field is required.' (length=46)
protected 'format' => string ':message' (length=8)
json_encode($validation->messages) returns
{}
Question: how do I return all the validation error messages for all fields as a JSON structure in Laravel 4?
Simply use toJson()
method.
return $validator->messages()->toJson();
Here is another way that let u add HTTP code to the response:
return Response::json($validation->messages(), 500);
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