Validating Laravel API requests

Prakash Chhetri
2 min readDec 28, 2020

Laravel provides a number of ways to validate incoming requests into your web application. The easiest one would be to use the default validate method which is made available to all the incoming HTTP requests.

There are several validation rules that come in with laravel which makes data validation easier as well as a lot quicker than writing your own validation logic from scratch. Not only that, but it also provides the ability to write your own validation logic wherever required.

You can learn more about Validation within Laravel at https://laravel.com/docs/8.x/validation#introduction

The first step would be to validate the requests using the validate method.

public function store(Request $request)
{
$validated = $request->validate([
'username' => 'required|unique:users|max:20',
'email' => 'required|unique:users',
]);

// The userdata is valid

In this case, if the validation fails, the user is redirected back to the form page where the request originated from and will make validation errors as well as request input available in the session (Read More). But the question here is when we are sending API requests, do we necessarily use forms? If not, where will be users be redirected to?

This is where we start receiving the 404 error when the validation fails when we are sending API requests.

This is because the application is expecting the request to be a form request. We can easily let the application know that the request we are sending is an API request and the response we expect is a JSON response.

We can set the header to Accept: aplication/json and this should do the trick.

--

--