Ilya Kolesnikov
Ilya Kolesnikov

Reputation: 652

Check Auth::user() from middleware

I try to check in middleware if user is authenticated by calling Auth::user() But it returns null. I call this middleware last in list of protected $middleware section in Kernel.php. Is there an way to check from middleware if user is authenticated or how I should do it another way?

Addition: I'm using Zizaco Entrust. May be it is why it doesn't work And I'm using Laravel 5.5

my app/HTTP/Kernel.php:

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\FirstLoginPasswordChange::class,
    ];

my FirstLoginPasswordChange middleware:

use Illuminate\Support\Facades\Auth;
use Zizaco\Entrust\Entrust;

    public function handle($request, Closure $next)
    {
        dd(Auth::user()); // returns null
// or
        dd(Auth::check()); // returns false
// or
        dd(\Entrust::user()); // returns null

        return $next($request);
    }
}

Upvotes: 2

Views: 6969

Answers (2)

Ilya Kolesnikov
Ilya Kolesnikov

Reputation: 652

problem solved by moving middleware from protected $middleware section in Kernel.php to protected $routeMiddleware section in Kernel.php using this article: http://laraveldaily.com/password-expired-force-change-password-every-30-days/

Upvotes: 3

NaturalDevCR
NaturalDevCR

Reputation: 852

To check if user is authenticated you can do as Laravel Docs states:

use Illuminate\Support\Facades\Auth; //be sure to add the facade

if (Auth::check()) {
    // The user is logged in...
}

If you are trying to get user details and do some logic, then you can do this in your middleware:

{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{


    $role = Auth::user()->role; //Obtenemos el rol del usuario

    if ($role != "user"){
        return redirect('/logout');
    }

    return $next($request);

}

}

Upvotes: 1

Related Questions