Reputation: 664
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?
?serial
? FormRequest
class for every method?if (..) {return response()->json([..], 400);}
Upvotes: 1
Views: 1668
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
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
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