1 year ago

Auth::user() returns null with using global middleware

Posted 1 year ago by lonerunner

I am trying to create last user activity, and i've been reading some instructions on middlewares but i am confused, i previously built middleware for role check and that successfully works when i put middleware in $routeMiddleware because that should be routed middleware, now i am reading on and there is global middleware which says:

If you want a middleware to run during every HTTP request to your application, list the middleware class in the $middleware property of your app/Http/Kernel.php class.

So this means middleware would run every possible time, which i need.

So i created middleware LastActivity in \App\Http\Middleware\LastActivity.php

I registered middleware in global middleware in Kernel.php

    protected $middleware = [

And if i try to simply do this in middleware:

$user = Auth::user();


I get null or false, as user is not loged in.

But if i move middleware to web group

   protected $middlewareGroups = [
        'web' => [

Than it works, so why it doesn't catch in global? Am i missing something here, i still didn't tested with api requests but i'm afraid it won't work per explanation i read on middleware page. But i will need it for api requests too, so global middleware would be solution.

Please sign in or create an account to participate in this conversation.