Dependency Injection and Service Container in Laravel [Step-by-step Guide]

Dependency injection is a method “used to detach hard-coded class dependencies.” The dependencies are inserted at run-time, which allows for greater pliability as dependency execution may be easily reciprocated.

Service Container in Laravel is a “Dependency Injection Container and a Registry for the application.” Laravel Container is a powerful tool for managing dependencies and storing objects for various purposes; for example, You can store objects and use them in Facades.

Dependency injection is commonly used even with request access, and we mostly inject it.

public function __construct(Request $request)

Let us look beneath the surface because knowing how things work is always better than memorizing them.

When you inject the object into your class, Container uses the Reflection API to inspect your constructor method and retrieve what you have defined as a dependency.

Dependency injection via routes

We type-hint any dependencies needed by the routes into the callback function like this:

<?php

class Property
{
   //
}

Route::get('/', function (Property $property) {
  die(get_class($property));
});

In the example above, hitting your application’s / route will automatically determine the Property class and inject it into your route’s handler.

So, when we do die(get_class($property)), we would see an empty class, which implies that we could easily use the property class.

Here are the steps to implement dependency injection in Laravel:

Step 1: Install the Laravel Project.

Type the following command.

composer create-project laravel/laravel DI --prefer-dist

Configure the database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=di
DB_USERNAME=root
DB_PASSWORD=mysql

We need to seed the Users table

Type the following command.

php artisan make:seeder UsersTableSeeder

Step 2: Write the queries and seed the table.

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
         DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
          DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
           DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
            DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
             DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
    }
}

Type the following command in your terminal.

php artisan db:seed

It will create the rows for our table.

Step 3: Dependency Injection Code.

Make one controller called UserController by typing the following command.

php artisan make:controller UserController --resource 

We need to make one web route for our application.

In the web.php file, write the following line of code.

Route::get('/users', 'UserController@index');

We need to include our User.php model in the UserController.php file.

use App\User;

We also need to write the constructor for the class to inject the dependencies.

/**
     * The user repository implementation.
     *
     * @var UserRepository
     */
    protected $users;

    /**
     * Create a new controller instance.
     *
     * @param  User  $users
     * @return void
     */
    public function __construct(User $users)
    {
        $this->users = $users;
    }

In the index() function, write the following lines of code.

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $id = 2;
        $user = $this->users->find($id);
        return $user;
    }

In a real-life example, we need to pass the $id as a parameter of that function, but this is a demo, so not required here.

Start the laravel server by typing the following command.

php artisan serve

Hit the following URL.

http://localhost:8000/users

You will see an output like this.

{
 "id": 2,
 "name": "qvzbXlneUl",
 "email": "W4PvNyLAdX@gmail.com",
 "created_at": null,
 "updated_at": null
}

We successfully injected the class into the constructor and made one object of that model, and through that object, we can now access its method and display the data from the database.

In Laravel, you can also direct Inject the class into its method, and at that time, you do not need to build the object; laravel will make it for you through Resolution API.
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
 public function index(User $users)
 {
   $id = 2;
   $user = $users->find($id);
   return $user;
 }

That’s it for this tutorial.

1 thought on “Dependency Injection and Service Container in Laravel [Step-by-step Guide]”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.