Validation error messages as JSON in Laravel 5.3 REST

laravel, laravel-5, laravel-5.3, rest

Solution

You can do your validation as:

    $validator = \Validator::make($request->all(), [
       'organizationName' => 'required',
       'organizationType' => 'required',
       'companyStreet' => 'required'
    ]);

    if ($validator->fails()) {
       return response()->json($validator->errors(), 422)
    }

Problem

My app is creating a new entry via a `POST` request in an api end point. Now, if any validation is failed then instead of returning an error json, laravel 5.3 is redirecting the request to 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 issue with validation then the entity will be successfully added in the database, but if there is issue with validating the request then instead of sending all the error messages as a json response it redirects back to the home page. How i can set the validate return type to json, so with every request if the validation failed then laravel will send all the error messages as json by default.

Original source