In this article we will discuss Laravel dependency injection. This lesson will briefly explore dependency injection using an example from Laravel 8.
In Laravel, dependency injection is frequently used. Even with access, we mainly inject it. When you try to inject an object into your class, Container inspects your constructor method using the Reflection API to find the dependencies you've specified.
An effective solution for handling class dependencies and conducting dependency injection is the Laravel service container. The term "dependency injection" is a fancy way of saying that the constructor is used to "inject" class dependencies into the class.
Let's attempt Laravel's dependency injection.
I want to create a TaskRepository to house all of the Task model's data access logic. If the application expands and you need to share some Eloquent queries throughout the program, this will be extremely helpful.
Step 1 : Create Task Model
Use the following command to construct the Task model after downloading the Laravel project and setting up the database.
php artisan make:model Task -fm
now, insert the following code into your tasks migration file.
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->unsignedBigInteger('user_id');
$table->timestamps();
});
}
Now open TaskFactory to create some dummy data.
database/factories/TaskFactory.php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Task;
use Faker\Generator as Faker;
$factory->define(Task::class, function (Faker $faker) {
return [
'title' => $faker->paragraph,
'user_id' => 1
];
});
Now open terminal and run below command
php artisan tinker
//then
factory(\App\User::class,10)->create()
//then
factory(\App\Task::class,10)->create()
//then
exit
You will see some fictitious data generated in our tasks and users database after running this command.
Step 2 : Make Auth
With just a few straightforward commands, you can quickly build all the routes and views you require for authentication using Laravel's laravel/ui package:
composer require laravel/ui --dev
php artisan ui vue --auth
Now you have to register your account cause we find out all of our task of a specific user. So do it. After doing it we have to setup our route.
Step 3 : Setup Route
Route::get('/user', 'TaskController@index');
Step 4 : Create Task Repositories
In order to store all of our data access logic for the Task model, I now want to construct a TaskRepository. So let's make a directory called app/Repositories and add a class called TaskRepository to it.
You are allowed to construct as many additional directories as necessary because the PSR-4 auto-loading standard ensures that all Laravel app folders are automatically loaded: You can also read this article if you're not familiar with the PS-R 4 autoloader.
Paste the following code into TaskRepository now.
namespace App\Repositories;
use App\User;
use App\Task;
class TaskRepository
{
/**
* Get all of the tasks for a given user.
*
* @param User $user
* @return Collection
*/
public function get_all_task_for_a_given_user(User $user)
{
return Task::where('user_id', $user->id)
->orderBy('created_at', 'asc')
->get();
}
}
Step 5 : Injecting The Repository
Once our repository has been established, all we need to do is "type-hint" it in the TaskController constructor and use it in our index route. Our dependencies will be automatically injected into the controller instance because Laravel uses the container to resolve all controllers:
app/Http/Controllers/TaskController.php
namespace App\Http\Controllers;
use App\Task;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repositories\TaskRepository;
class TaskController extends Controller
{
/**
* The task repository instance.
*
* @var TaskRepository
*/
protected $tasks;
/**
* Create a new controller instance.
*
* @param TaskRepository $tasks
* @return void
*/
public function __construct(TaskRepository $tasks)
{
$this->middleware('auth');
$this->tasks = $tasks;
}
/**
* Display a list of all of the user's task.
*
* @param Request $request
* @return Response
*/
public function index(Request $request)
{
return $this->tasks->get_all_task_for_a_given_user($request->user());
}
}
Note just how the constructor "injected" our TaskRepository class dependencies into the class. Now, if you go to this route's url, you will see the information below. For a certain user, we returned a specified task.
Look at this now to see the list of tasks we created for each individual user using Laravel dependency injection.
Hope this article will help you.
Read This Article : PSR-4 Autoloading Your PHP Files using Composer Tutorial
Read This Article : Dependency injection from laravel.com