Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation always returns 200 OK from API

I want to separate my validator with my controller, but API always responds with a 200 OK in Postman.

Request validation:

class PostRequest extends FormRequest
{
    use Types;

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        // $auth = $this->request->user();
        return [
            'name'       => 'required|string|max:255',
            'country_id' => 'required|exists:countries,id',
            'city'       => 'required|max:255',
            'phone_no'   => 'required|regex:/[0-9]{10,13}/',
            'occupation' => 'required|max:255'
        ];
    }
}

SenderController:

public function store(PostRequest $request)
{
    $auth = $request->user();

    $sender = Sender::create([
        'name'          => $request->name,
        'country_id'    => $request->country_id,
        'city'          => $request->city,
        'phone_no'      => $request->phone_no,
        'occupation'    => $request->occupation
    ]);
    return new Resource($sender);
}

When I'm sending a request without name, it will return a response with a status of 200. I want to display $validator->errors() in my response when I forget to input name. How can I do that?

Postman

Route and call:

Route::post('sender', 'V1\SenderController@store');

POST: localhost:8000/api/v1/sender
like image 518
Saengdaet Avatar asked Sep 26 '18 15:09

Saengdaet


People also ask

How do I validate a request in laravel API?

You can set any key / pair values in the json, “$validator->errors()” send the error with attribute name in the response. Step 6 : Add “LoginRequest. php” file in the API's controller file. Step 7 : Add “LoginRequest”as a parameter in the controller which you will call from API.

How does laravel validation work?

The validate method accepts an incoming HTTP request and a set of validation rules. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user.

What does validate return in laravel?

Validation is the most important aspect while designing an application. It validates the incoming data. By default, base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP requests with a variety of powerful validation rules.


1 Answers

You should make sure you're sending the request with the Accept: application/json header.

Without that - Laravel won't detect that it's an API request, and won't generate the 422 response with errors.

like image 172
Tspoon Avatar answered Oct 01 '22 07:10

Tspoon