AppDividend
Latest Web Development Tutorials

Laravel Dependency Injection Tutorial Example

Laravel 5.5 Dependency Injection Tutorial

1,418

Laravel Dependency Injection Tutorial Example is today’s leading topic. We are using Laravel 5.5 so, it is Laravel 5.5 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 the 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 Tutorial Example

We will be going to understand with an example.

Step 1: Install Laravel 5.5 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.

Related Posts
1 of 10
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 to 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 Dependency Injection Tutorial is finally over.

For more information, please follow this Link: https://laravel.com/docs/5.5/container

Leave A Reply

Your email address will not be published.