Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jcord's avatar
Level 4

API validation not AJAX requests

Hi All, I'm creating a very basic api within an already existing laravel application, however i'm struggling to understand how to perform the validation of data submitted to an api endpoint. Within the main laravel application we utilise form requests to carry out the majority of validation but from my testing and reading of the docs these don't seem to be applicable to an API as if the request is not an AJAX request then it will perform a redirect. Not all of our consumers will be consuming the api through ajax.

Its probably really simple and i am making hard work of it (as is usually the case!) but i would like to separate validation from the controller if possible.

Thanks Jamie

0 likes
4 replies
douglasakula's avatar
public function myApiCall(Request $request)
    {
        $validaton_rules = [
            'field1'    => 'required|date|date_format:d-m-Y',
            'field2'    => 'required',
            'field3' => 'required|integer|exists:restaurants,id',
        ];

        $validator = Validator::make($request->all(), $validaton_rules);

        if ($validator->passes()) {
                
            //do what api end point should do

        } else {
            return Response::json(['errors' => $validator->messages()->toArray()], 200);
        }

        return Response::json($output);
    }

You could use something like above to validate requests send to your api and return appropriate validation errors

douglasakula's avatar

If you prefer not to have the validation rules within the controller - you could create a request object for the api endpoint (to be placed in your app/Http/Requests folder) that does the validation - but above is simple and could get the job done

jcord's avatar
jcord
OP
Best Answer
Level 4

Hi,

Thanks for the reply. I am aware of the validator and had tried the above but still got the 302 redirects in postman. From doing some more research and looking at the source code it seems that setting Content-Type application/json like i was is not enough, it requires the additional header of Accept application/json. At this point it returns the 422 upon failed validation.

Thanks for looking at my question anyhow.

Jamie

zion's avatar

You can check if the request is ajax:

if($request()->ajax()) {
// Do something
}

Please or to participate in this conversation.