Benedict
Benedict

Reputation: 390

How to display custom vaildation error messages for API requests?

            try{
                $request->validate([
                    'aadhar' => 'required|digits:12|numeric',
                    'name' => 'required|string|max:511',
                    'dob' => 'required|date_format:Y-m-d',
                    'email' => 'required|email|max:255',
                    'address' => 'required|string',
                    'insuranceid' => 'required|digits_between:1,15|integer',
                    'password' => 'required|min:59|max:60',
                ]);
                }
            catch(Exception $error){
                    $message = $error->getMessage();
                    $status_code=400;
                    return response()->json(["message" => $message,"status_code" => $status_code]);
                }

This is my piece of code for the validation of the request parameters sent to an API. The documentation gives details only about custom error messages in case of a form request.

The validation errors give the default message "The given data was invalid" but I would like to know which of the parameter was invalid. How do I give custom validation error messages for API requests validation?

Upvotes: 2

Views: 2082

Answers (2)

Kenny Horna
Kenny Horna

Reputation: 14241

First of all, to decouple your code, you could use a Form Request class. From the docs:

For more complex validation scenarios, you may wish to create a "form request". Form requests are custom request classes that contain validation logic.

This class contains two methods:

1 - rules, the place where you specify your rules, it should return an array of rules.
2 - authorize that return a boolean,this method control who is allowed to perform this request. By default is set to false, so every call will be rejected.

So, in your case, it should be something like this:

First, create your custom Request class executing this artisan command in your console:

php artisan make:request CreateCustomObjectRequest

This wil create a new class under app/Http/Requests:

class CreateCustomObjectRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        // Implement here your Auth validation, something like:
        return auth()->check();
        // or just return "true" if you want to take care of this anywhere else.
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'aadhar' => 'required|digits:12|numeric',
            'name' => 'required|string|max:511',
            'dob' => 'required|date_format:Y-m-d',
            'email' => 'required|email|max:255',
            'address' => 'required|string',
            'insuranceid' => 'required|digits_between:1,15|integer',
            'password' => 'required|min:59|max:60',
        ];
    }
}

And then, in your controller, instead of inject a regular Request object, we are gonna use this custom Request object:

use App\Http\Requests\CreateCustomObjectRequest;

// ...

    public function store(CreateCustomObjectRequest $request)
    {
        // the rest of your controller logic.
    }

Now, the part you are really interested in. To return errors in a json way you should add the next header when making a request:

Accept: Application/json

This header will tell Laravel that the output should be a json response, so it will convert it to json. Note that this will only work with the validation rules and when returning objects like return $someObject. To more further customization you shoud use something like:

return response()->json(['data' => $someObject], 200);

Upvotes: 5

online Thomas
online Thomas

Reputation: 9381

$validator = Validator::make($request->all(), [
        'password' => [
            'required',
            'confirmed',
            'between:8,55'
        ]
    ]);

    if ( $validator->fails() ) {
        return response()->json( [ 'errors' => $validator->errors() ], 400 );
    }

Upvotes: 2

Related Questions