Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation error messages as JSON in Laravel 5.3 REST

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.

like image 234
rakibtg Avatar asked Oct 27 '16 06:10

rakibtg


2 Answers

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)
    }
like image 106
Amit Gupta Avatar answered Nov 20 '22 03:11

Amit Gupta


The validation used in the question looks as per the recommendation by laravel. The reason of redirection is that it throws an exception which you can easily catch using the code below. So it's better to use the recommended way of code instead of re-writing framework's code again :)

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);
}
like image 24
Imran Zahoor Avatar answered Nov 20 '22 02:11

Imran Zahoor