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?
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());