2

How to send send error message in json format to postman in laravel 5.4

 //Controller
 public function store(Request $request)
 {
     $validator = Validator::make($request->all(),[
        'department_name'  => 'required',
     ]);
     if($validator->fails())
     {
        return $validator->errors()->all();
     }
     Department::create($request->all());

     return Response::json(['message' => 'Added','status' => 201],201);
}
4
  • Why don't you use response json like this : if ($validator->fails()) { return response()->json($validator->messages(), 200); } or a status other than 200 then in the client side test if status equal the new value then show errors ! Commented Jun 22, 2017 at 11:42
  • No Maraboc it dint work, I'm getting an exception if I add validation, anyway thanks for the help. Commented Jun 22, 2017 at 12:02
  • 1
    What kind of exception ?? try this one if ($validator->fails()) { return response()->json(['errors'=>$validator->errors()]); } !! Commented Jun 22, 2017 at 13:17
  • It's working now Maraboc,Thank you. Commented Jun 22, 2017 at 13:19

1 Answer 1

2

You can simply return the validation errors as json response like this :

if ($validator->fails()) { 
    return response()->json(['errors'=>$validator->errors()]); 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.