weekapaug
weekapaug

Reputation: 332

Laravel Validation Error Handing

I have a statement in my code like this

  return response()->json([
     'error'=>$validator->errors()->all()
  ]);

When I view the response it has curly braces around it and looks like an object and it throws an error in the console that says

SyntaxError: Unexpected end of JSON input at parse ()

What do I need to change to get the format that my ajax call can interpret?

This code worked inside of a controller but when I move it to a different page it breaks so it seems there is something in the controller that corrects this, but is missing on my own page. Any ideas?

Upvotes: 0

Views: 46

Answers (2)

Leslie
Leslie

Reputation: 11

obviously the json structure is wrong, u show use json_encode() to handle the $validator->errors()->all();

return response()->json([
 'error'=>json_encode($validator->errors()->all())

]);

Upvotes: 1

Jobayer
Jobayer

Reputation: 1231

you can try something like below code

$data['success'] = false;
$data['message'] = $validator->errors()->all();
echo json_encode($data);

Upvotes: 1

Related Questions