Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Dependency Inject Auth

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;
like image 756
James Satori-Brunet Avatar asked Nov 05 '14 14:11

James Satori-Brunet


People also ask

How Laravel dependency injection works?

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.

Why we use Service Container in Laravel?

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.

What is the Service Container?

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.


1 Answers

You should type hint Illuminate\Auth\AuthManager:

public function __construct(Illuminate\Auth\AuthManager $auth)
{
  $this->auth = $auth;
}
like image 111
Bogdan Avatar answered Sep 29 '22 07:09

Bogdan