yoeriboven's avatar

Inject authorized User or get it from auth()->user()?

In a controller I am calling a repository method to get data. Should I use auth()->user() in the repository method or inject it as a function argument?

What's the recommended approach here?

0 likes
4 replies
mitrich's avatar

use dependency injection if you want to have it as argument of function

BGWeb's avatar

Not necessarily, unless you call the create() method on the injected object. If you want access to the current user at the controller level, it can be pretty challenging to inject it in the constructor. For example,

class MyController extends Controller
{
    private $user
    public function __construct(User $user) 
    {
        $this->user = auth()->user();
    }
}

will not work.

However, you can access auth()->user() later in the controller in another method:

...
public function setControllerUser(User $user)
{
    $this->user = $user
}
...

and then call your method like so $controller->setControllerUser(auth()->user());

Snapey's avatar

you could put this in the repository constructor or inject it as an argument?

public function __constructor
{
    $this->user = Auth::user();
}

This would save you injecting it on every repository method since its unlikely to change during the request lifecycle.

I just use it direct because I don't care that one day I might swap out the framework. I might also be hit by a bus.

Please or to participate in this conversation.