uksarkar
5 months ago
458
6
Laravel

auth() helper is not working on middleware

Posted 5 months ago by uksarkar

I create a middleware, that's calling on every request. My middleware like this :

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class UrlAndActivityMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(auth()->check()){
            $expiresAt = Carbon::now()->addMinutes(5);
            Cache::put('online-user-' . auth()->user()->id, true, $expiresAt);
        }

        return $next($request);
    }
}

But it's giving me this error ,

 ErrorException (E_NOTICE)
Trying to get property 'id' of non-object

I also tried,

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;

class UrlAndActivityMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = Auth::user();
        if(!$user){
            $expiresAt = Carbon::now()->addMinutes(5);
            Cache::put('user-is-online-' . $user->id, true, $expiresAt);
        }

        return $next($request);
    }
}

It also giving me the same error, and also on $request->user()->id. What am I missing here?

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