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

JoeT's avatar
Level 1

Authentication working on routes.php but not on api.php

I have an app which until now only used routes.php.

I am storing all routes that need to be secured within

Route::middleware('auth')->group(function () { //...routes }

I now have a requirement to use the api so that I can make a call to it using ajax to pull in some data from some models.

Using the same method as above, despite the user being signed in, they're redirected to the login page (if going to the api route directly in the browser).

Why is this?

0 likes
6 replies
JoeT's avatar
Level 1

To be clearer, using this within routes.php results in "Authenticated user" when visiting /get-tags.

When using it in api.php and visiting /api/get-tags, it results in "Not authenticated".

Route::get('/get-tags', function(){
    if (Auth::check()) {
        return "Authenticated user";
    }else{
        return "Not authenticated";
    }
});
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

If you have a routes.php file it must be an old laravel version? Now it's web.php. Anyways. Api is stateless by default so you cannot be signed in with sessions. Either use routes.php or use something like sanctum for to enable sessions for those routes. Personally I would go for the first (or make a new route file for ajax)

JoeT's avatar
Level 1

My bad, I meant web.php (within routes directory). I'm using Laravel 9.

I will use web.php instead. I've misunderstood the purpose of the api routes.

JoeT's avatar
Level 1

@Sinnbeck Thanks but still learning the basics at the moment. Will look into it for the next project when not feeling so burnt out.

Thanks for your help.

Sinnbeck's avatar

@JoeT yeah just adding them into web.php is easy and works out of the box

Please or to participate in this conversation.