0

I have this global middleware that updates user's last activity

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Closure;

class HandleLastActivity
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (auth()->user()) {
            $user = auth()->user();
            $user->lastActivity = now();
            $user->save();
        }

        return $next($request);
    }
}

but auth()->user() is always null. I'm using sanctum and it works in routes under auth middleware.

env

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=.mydomain.com

SANCTUM_STATEFUL_DOMAINS=mydomain.com,www.mydomain.com,api.mydomain.com

config/auth.php

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'sanctum',
            'provider' => 'users',
        ],
    ],
  • 1
    global middleware are earlier in the stack than route middleware, anything that needs sessions won't be working since the middleware that starts the session hasn't ran yet ... if you want to log this information for the User do it as an "after middleware", do the insert after you call `$response = $next($request);`, then return the response after the insert – lagbox Nov 12 '20 at 09:22
  • if sanctum is not your default guard you should specify sanctum as the guard `auth('sanctum')->user()` – ml59 Nov 12 '20 at 10:52
  • @lagbox solution worked. Thanks to you two guys! –  Nov 12 '20 at 17:49

0 Answers0