protocod
protocod

Reputation: 107

Handle validator to return json

Laravel throw an exception at $validator->fails() call.

Ok, I just want to create a stateless register method in ApiController.php with Laravel 5.7.

I used the Validator facade to check the sent data.

    $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email|unique',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);
        if ($validator->fails())  {
            return response()->json(['error'=>$validator->errors()], 
                                           Response::HTTP_UNAUTHORIZED);
        }

But, when I use xdebug, I see something strange. The fails methods seems throw an exception.

Laravel send an error HTML page with title:

Validation rule unique requires at least 1 parameters.

The route is used in api.php

Route::post('register', 'Api\UserController@register');

Do you have an explanation for this? Thx for reading.

Upvotes: 1

Views: 217

Answers (2)

Mike
Mike

Reputation: 862

The syntax for unique rule is unique:table,column,except,idColumn. So i changed it for you to use the users table. If you don't want to use the users table change the users part behind unique:

$validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required',
            'c_password' => 'required|same:password',
]);
if ($validator->fails())  {
    return response()->json(['error'=>$validator->errors()], 
        Response::HTTP_UNAUTHORIZED);
}

For more information on the unique rule see this: https://laravel.com/docs/5.7/validation#rule-unique

Upvotes: 1

Kenny Horna
Kenny Horna

Reputation: 14251

In your API request add the following header:

...
Accept: application/json // <-----

This will tell Laravel that you want a response in a json format.


Note: this is different to the Content-type: application/json. The later indicates the format of the data tha is being sent in the body.

Upvotes: 0

Related Questions