Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - how to return all validation error messages for all fields as a JSON structure?

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?

like image 396
mtmacdonald Avatar asked Oct 17 '13 08:10

mtmacdonald


2 Answers

Simply use toJson() method.

return $validator->messages()->toJson();
like image 91
Andreyco Avatar answered Oct 04 '22 15:10

Andreyco


Here is another way that let u add HTTP code to the response:

return Response::json($validation->messages(), 500);
like image 34
Elia Weiss Avatar answered Oct 04 '22 17:10

Elia Weiss