Semyon Zhikharev
Semyon Zhikharev

Reputation: 664

Laravel 5 API request validation

I'm working with Laravel 5 API. I have a few methods with similar request parameters

For example to check the licence status or get the settings file you need to provide the ?serial=licence_serial_number parameter.

I need to return 400 error code, when the user didn't provide the serial parameter, and 403 error code, when the user is trying to get information about the licence of another user.

What is the best practice to organise validation and error handling of these kind of requests?

Upvotes: 1

Views: 1668

Answers (3)

Nguyen Hiep
Nguyen Hiep

Reputation: 71

$request->wantJson(), with a request with Header Accept=application/json Will tell Laravel to return json validation error instead of goback with errors

Upvotes: 1

Dennis Schepers
Dennis Schepers

Reputation: 573

It depends on a few things acctualy:

If your always validating the same thing for all requests: Go With a Middleware Solution.

But if some or multiple requests validate different things then I would advise on using the new FormRequest from Laravel.

It handles the validation for your request perfectly, and also allows you the define the error responses per request.

Also a middleground is an option, Let middleware validate the thing that needs to be validated always. And FormRequests to handle the variable validation.

If you have similar FormRequests, consider using inheritance to prevent code duplication like a good SOLID programmer :-)

Upvotes: 0

Gal Sisso
Gal Sisso

Reputation: 1959

Middleware will probably be the best choice but you could also use the Request method.Inline validation is a bad practice as its ignore the most basic rule of programming - Dont Repeat Yourself.

In case you decide go for the request option you aren't supposed to create the authorize method for each class,instead create 1 parent witch will handle this and the other sub classes will just have the rules method.

Upvotes: 0

Related Questions