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

HUGE_DICK_10_INCHES's avatar

Accept only ajax request on api routes in laravel

Is there a way to accept only ajax requests on api routes?

0 likes
5 replies
bobbybouwmann's avatar

If you really want it save you can use your own header and require that. So your frontend always needs to send a specific header which is accepted by the middleware.

By default this is just fine, normally you also have authentication on the api right? :D

bobbybouwmann's avatar

In your api request you would send a header with the request and you would check for that in your middleware

So let's say your application is called MyApp

curl --header "X-MyApp: 123" www.example.com/api/some/route

// In your middleware
public function handle($request, \Closure $next)
{   
    if (!$request->ajax() || !$request->headers->contains('X-MyApp')) {
        return response('Forbidden.', 403);
    }

    return $next($request);
}

Note: The string can be anything. Could be the id of user or a company id for example. You can use that to check that as well. However you don't have to do anything with that header. In my example I also don't check for the value, just if the header exists.

Let me know if this makes any sense!

Please or to participate in this conversation.