Hey Artisan , in this tutorial we are going to learn about laravel dependency injection. Dependency injection in laravel 8 example tutorial is going to be discussed briefly in this tutorial.
Dependency injection is commonly used in Laravel. Even access to Request we mostly inject it.When you try to inject an object into your class, Container uses Reflection API to inspect your constructor method and retrieves what you have defined as a dependency.
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.
I want to define a TaskRepository
that holds all of our data access logic for the Task
model. This will be especially useful if the application grows and you need to share some Eloquent queries across the application.
Step 1 : Create Task Model
After downloading laravel project and having setup database, just run below commnad to create Task model.
php artisan make:model Task -fm
now open your tasks migration file and paste this following code.
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
After running this command you will see some fake data generated in our tasks and users table.
Step 2 : Make Auth
Laravel's laravel/ui
package provides a quick way to scaffold all of the routes and views you need for authentication using a few simple commands:
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
routes/web.php
Route::get('/user', 'TaskController@index');
Step 4 : Create Task Repositories
Now i want to define a TaskRepository
that holds all of our data access logic for the Task
model.So, let's create an app/Repositories
directory and add a TaskRepository
class.
Remember, all Laravel app
folders are auto-loaded using the PSR-4 auto-loading standard, so you are free to create as many extra directories as needed: If you don't know what is PS-R 4 autoloader, you can also read this article.
Read also : PSR-4 Autoloading Your PHP Files using Composer Tutorial
Now open TaskRepository and and paste this following code.
app/Repositories/TaskRepository.php
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 is defined, we can simply "type-hint" it in the constructor of our TaskController
and utilize it within our index
route. ince Laravel uses the container to resolve all controllers, our dependencies will automatically be injected into the controller instance:
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());
}
}
Look here our TaskRepository class dependencies are "injected" into the class via the constructor. Now if you visit this route url, then you will see the following data. We returned specific task for a specific user.
Now have look, we can see our specific user task list and we did it using laravel dependency injection.
Great, we just did it. hope it will helpful for you. If you like this tutorial, then please share with your friends.
#laravel-6 #laravel #dependency-injection #constructor