How do I dependency inject Auth in Laravel?
Like this:
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
If I do that then this does not work:
$user_type = Auth::user()->user_type;
In Laravel, dependency injection is the process of injecting class dependencies into a class through a constructor or setter method. This allows your code to look clean and run faster. Dependency injection involves the use of a Laravel service container, a container that is used to manage class dependencies.
The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.
A Service Container (or dependency injection container) is simply a PHP object that manages the instantiation of services (i.e. objects). For example, suppose you have a simple PHP class that delivers email messages. Without a service container, you must manually create the object whenever you need it: Copy.
You should type hint Illuminate\Auth\AuthManager
:
public function __construct(Illuminate\Auth\AuthManager $auth)
{
$this->auth = $auth;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With