0

When I am trying to return Auth::user() or return $request->user(), the handle($request, Closure $next, ...$guards) function (in Authenticate.php middleware) returns null. This middleware execute for every route. I am trying to return Auth::user() because i need an email of currently logged user and returning Auth::user() is for checking if I can get informations about currently logged user.

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Closure;
use Illuminate\Support\Facades\Cookie;
use PHPOpenSourceSaver\JWTAuth\Exceptions\TokenExpiredException;
use PHPOpenSourceSaver\JWTAuth\Exceptions\TokenInvalidException;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        
        if (!$request->expectsJson()) {
            return route('login');
        }
    }

    public function handle($request, Closure $next, ...$guards)
    {
        return Auth::user();
        return $next($request);
    }
}
5
  • return Auth::user() ? Return it to where? Commented Sep 30, 2022 at 23:28
  • I am trying to return it in postman Commented Sep 30, 2022 at 23:30
  • Welcome to SO ... what is the default guard? Commented Sep 30, 2022 at 23:40
  • 'guards' => [ // 'web' => [ // 'driver' => 'session', // 'provider' => 'users', // ], 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ], Commented Sep 30, 2022 at 23:50
  • what is the default set as? an please add this information to your answer in a code block not in the comments Commented Oct 1, 2022 at 0:30

1 Answer 1

1

The handle() method in the parent class Illuminate\Auth\Middleware\Authenticate performs the actual authentication. Since you've overridden this method and not calling the auth logic, authentication isn't performed and thus Auth::user() returns null.

You can remove the handle() method from your middleware, and add the debug-line return Auth::user(); in redirectTo() instead (just before the if()).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.