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

raultrysw's avatar

Auth::user returns null on route changed

Hi, I am the author of this other post: https://laracasts.com/discuss/channels/requests/i-dont-cant-to-get-the-cookie

I am beginning to write posts here with the intention of getting help to my project...

Currently, I am implementing the authentication, and in /api/login I am writting the login logic that is as follows...

public function login(Request $request) {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            return redirect()->intended('/articles');
            // return var_dump(Auth::user());
        } else {
            return response('bad petition');
        }

    }

If I return Auth::user I get the user found on the login, but if I aim to recover the user later in other petition, I get null, for example in /articles:

public function index(Request $request)
    {
        //
        $posts = Article::paginate(10);
        //return View('pages.articles.index', ['posts' => $posts, 'token' => Cookie::get('token')]);
        return response(var_dump(Auth::user()));
    }

Please, help, I was through all day trying to solve the problem!

0 likes
5 replies
jlrdw's avatar

Just use session normally (Auth out of the box), A session cookie is stored anyway that tracks the session. Believe me if you follow the guide (docs) you will be fine. I have used laravel since ver 4.2. Now I use 5.5.

If you start tweaking this and that you get into a bad chain reaction of what did I do wrong

Just my 4.27 cents.

Cronix's avatar

Currently, I am implementing the authentication, and in /api/login I am writting the login logic that is as follows.

You mentioned using api. By default, sessions aren't available to the api routes, so if you log in it won't persist because it has no way to track you in between calls to the server without a cookie for sessions. Usually you don't "log in" to an api with a username/password, you use an api key/token. You'd do that with something like passport: https://laravel.com/docs/5.6/passport

jlrdw's avatar

@Cronix don't forget we are dealing with an author

Hi, I am the author of this other post:

Just kidding

Snapey's avatar

also, if these are API routes then you would not use redirects

raultrysw's avatar

That has already solved, thanks for your all help :)

But I got another question, question sorry for that :(

Please or to participate in this conversation.