AppDividend
Latest Code Tutorials

Laravel 6 Dependency Injection Example | DI In Laravel

0

Laravel Dependency Injection Tutorial Example is today’s leading topic. We are using Laravel 6 so, and it is a Laravel 6 Dependency Injection TutorialDependency injection is the phrase that necessarily means the class dependencies that are “injected” into a class via a constructor or, in some cases, “setter” methods.

We can inject the classes into another class’s constructor and then get the object of that class, and through that object, we can access its methods and properties.

Laravel Dependency Injection Example

Content Overview

The Service Container in Laravel is a Dependency Injection Container and a Registry for the application.

Laravel Container is a powerful tool for that managing dependencies and stores objects for various purposes; for example; You can store objects and use them in Facades.

Dependency injection is commonly used in Laravel. Even access to Request, we mostly inject it.

public function __construct(Request $request)

Let us look beneath the surface because I believe that knowing how things work is always better than just memorizing it.

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

What is Reflection API in Laravel

Reflection is defined as a program’s ability to inspect itself and modify its logic at execution time.

PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions, methods, and extensions.

Additionally, the reflection API offers ways to retrieve doc comments for functions, classes, and methods.

Reflection is prevalent in PHP. There are several situations when you may use it even without knowing it.

Some of the PHP’s built-in functionally indirectly uses reflection API, one being the call_user_func function.

We will be going to understand with an example.

Step 1: Install Laravel 6 Project.

Type the following command.

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

Now, configure the database.

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

Now, 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 2: Dependency Injection Code.

Make one controller called UserController by typing the following command.

php artisan make:controller UserController --resource

Also, we need to make one web route for our application.

So, in the web.php file, write the following line of code.

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

We need to include our User.php model into 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 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 needed here.

Now, start the laravel server by the typing 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
}

So, we have successfully injected the class into the constructor and make one object of that model, and through that object, we can now access its method and displayed the data from the database.

In Laravel, you can also direct Inject the class into its method, and that time, you do not need even to build the object, Laravel will make 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;
 }

Our, Laravel 6 Dependency Injection Example | DI In Laravel is finally over.

See Also

Laravel http testing example

Laravel artisan example

Laravel gates example

Laravel queues example

Laravel mix example

Leave A Reply

Your email address will not be published.

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