1

How can I get current user in middleware? Laravel 5.6

When I try to include class

use Illuminate\Support\Facades\Auth;

and then

Auth::user()

I just get null

Middleware

namespace App\Http\Middleware;

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

class DebugbarMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        echo "<pre>"; var_dump(Auth::user()); echo "</pre>"; die();

        return $next($request);
    }
}

Authorization

$controller = new LoginController();
        $request = new Request();

        Auth::logout();

        $request->setLaravelSession(session()->driver(session()->getDefaultDriver()));

        $user = Auth::loginUsingId($id);

        if ($user) {
            $controller->authenticated($request, $user);
            return $this->sendResponse(['messages' => 'User authorization successfully'], 'M User authorization successfully');
        }

        return $this->sendError('User not found!');
Sizuji
  • 868
  • 2
  • 9
  • 26

1 Answers1

4

The global middleware stack runs prior to the session being started and authentication details being available.

Define this at the bottom of the 'web' group or in your route middleware.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • Defined at the bottom of route middleware, but Auth::user() still NULL – Sizuji Sep 10 '18 at 11:42
  • Did you remove it from the global stack as indicated in your comment? How did you verify you're authenticated and that Auth::user() is null? – Devon Bessemer Sep 10 '18 at 11:45
  • When I remove it from global stack, my middleware doesn't executes. I understand, that I authorized, cause I tried to get Auth::user() in controller, there I get everything – Sizuji Sep 10 '18 at 11:53
  • Yes... that's the whole point of route middleware, you need to specify the routes you want the middleware to run on (either in the controller constructor or in the route definition), but route middleware will execute after the session has been started for web routes. – Devon Bessemer Sep 10 '18 at 11:55
  • Thank you very much! I defined route with middleware in web routes and everything works perfect. – Sizuji Sep 11 '18 at 09:34