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

notecortes's avatar

[Solved] middleware('auth:api') redirect /home

Hi, i'm a new in laravel. I am working with Laravel 5.4 and i have a problem.

I've installed passport and seem work well, but i have done a route in api.php like this:

Route::get('movies2', function (Request $request) { //dd ($request); return Movie::all();//solo los 9 primeros })->middleware('auth:api');

if i use it with http://127.0.0.1:8000/api/movies2

i'm redirected to http://127.0.0.1:8000/home even if i am logged before. Could you help me?

edit: if I remove middleware('auth:api') it works ok.

Thanks a lot.

0 likes
3 replies
sutherland's avatar
Level 28

If you're logged in via a session on the website, just hitting the API endpoint isn't in your browser won't work. It won't be checking the session to see if you're logged in, it will be looking for an API token with the request. Since you aren't specifying a token, this throws an AuthenticationException.

The exception handler then takes this exception, checks your request and sees that it hasn't specified in the headers that it expects JSON. If it was expecting JSON, you would see a JSON response saying unauthenticated. Since it isn't expecting JSON, it redirects to the login page, which redirects to /home since you are logged in via a session. Confusing, but I expect that's the reason.

You'll need to use a tool like Postman if you want to play with your API endpoints so you can specify the required headers in the request.

1 like
notecortes's avatar

Hi!, yes it works!.

Thank you very much :). See you.

sutherland's avatar

Glad it worked out, please mark your question solved.

Please or to participate in this conversation.