Costin
Costin

Reputation: 197

Laravel 5.6 - get authenticated user outside controller without middleware

Long title. I have a singleton that can initialize at an arbitrary point. It might be called during the constructor of a controller, which makes it so I can't use auth middleware as it might not be built.

I need to get the user from somewhere, yet I can't find a way to do it. Session, request or middleware are not guaranteed to exist or be initialized. I checked the facades and nothing.

I'm sure there's a way to figure it out. Maybe someone else is more resourceful than me.

Upvotes: 0

Views: 526

Answers (1)

Costin
Costin

Reputation: 197

After tracing through the code, here's the issue:

A controller gets pipelined through the router, and the order goes like this:

->run controller __construct()

->then put it through the pipeline and run the middleware in order of importance

-> then perform other operations (ie call index() or whatever entry point the route wants)

Middleware is what handles sessions, request and auth etc... All middleware run between the controller __construct and the entry point.

So, in the controller, if you were to do something like:

__construct() {
    $this->middleware(function(Request $request, $next) {
       echo 'step 1';
    });

    echo 'step 2';

}

public function index() { echo 'step 3'; }

You would get:

step 2 <--- inside __construct scope (anything defined inside the middleware callback is not available here).

step 1 <-- outside __construct scope (but before index() scope)

step 3 <-- inside index, anything defined in step 1 is available here.

So, anything requiring those is guaranteed to exist before it is needed in the entry point functions, but not inside the constructor unless placed inside the middleware callback. So the best you can do is run the code in that 'in between'. In the end, making it available when you need it. There is a limitation here, you can get around it, but it is rather annoying.

I cannot find a way to get the user session before this point, i assume you'd have to read it from redis and resolve it yourself somehow as the laravel objects have not yet populated as it's too early in the pipeline.

Upvotes: 1

Related Questions