1

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?

  • Should I make a middleware to check if the user has provided ?serial?
  • Or should I make a different Laravel 5 FormRequest class for every method?
  • Or should I validate it directly in a controller with:
    if (..) {return response()->json([..], 400);}

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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 :-)

1 Comment

In case of using FormRequests, how can i define different types of responses when validation fails? FormRequests will just redirect user back with validation errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.