Validation error messages as JSON in Laravel 5.3 REST

My application creates a new entry through a POST request at the api endpoint.

Now if any check fails, instead of returning a json error, laravel 5.3 redirects the request to the home page.

Here is my controller:

 public function create( Request $request ) { $organization = new Organization; // Validate user input $this->validate($request, [ 'organizationName' => 'required', 'organizationType' => 'required', 'companyStreet' => 'required' ]); // Add data $organization->organizationName = $request->input('organizationName'); $organization->organizationType = $request->input('organizationType'); $organization->companyStreet = $request->input('companyStreet'); $organization->save(); return response()->json($organization); } 

If there is no problem with validation, then the object will be successfully added to the database, but if there is a problem with validating the request, instead of sending all error messages in the form of a json response, it redirects back to the main page.

How can I set the validate return type to json, so with every request, if the validation fails, laravel will by default send all error messages as json.

+6
source share
2 answers

You can do your check as:

  $validator = \Validator::make($request->all(), [ 'organizationName' => 'required', 'organizationType' => 'required', 'companyStreet' => 'required' ]); if ($validator->fails()) { return response()->json($validator->errors(), 422) } 
+4
source

The validation used in the question looks according to the laravel recommendation. The reason for the redirect is because it throws an exception, which you can easily catch using the code below. Therefore, it is better to use the recommended code method instead of re-writing the frame code :)

 public function create( Request $request ) { $organization = new Organization; // Validate user input try { $this->validate($request, [ 'organizationName' => 'required', 'organizationType' => 'required', 'companyStreet' => 'required' ]); } catch (ValidationException $e) { return response()->json($e->validator->errors(), 422); } // Add data $organization->organizationName = $request->input('organizationName'); $organization->organizationType = $request->input('organizationType'); $organization->companyStreet = $request->input('companyStreet'); $organization->save(); return response()->json($organization, 201); } 
+2
source

Source: https://habr.com/ru/post/1011748/


All Articles