Using Repository in Laravel



Asked by Anonymous 3 months ago

How to use repository in laravel?


Answered by Ryan Dhungel 3 months ago

The code is taken from Intermediate Level Tutorial from Laravel Documentation:

Using Repository in Laravel

TaskController.php


This is what we have in our task controller at the moment.

public function index(Request $request)
{
return view('tasks.index', [
'tasks' => $request->user()tasks()->orderBy('created_at', 'asc')->get();
]);
}


Move the function of getting all the taks of the user to the repository which will work as a bridge between database and the controller.


Create a new folder called Repository inside app folder.

TaskRepository.php

 

<?php

namespace App\Repositories;

use App\User;

class TaskRepository
{
public function forUser(User $user)
{
return $user->tasks()->orderBy('created_at', 'asc')->get();
}
}

TaskController.php

Inject the dependency to the constructor

 

// On top of the class
use App\Repositories\TaskRepository;

// Inside TaskController class
protected $tasks;
public function __construct(TaskRepository $tasks)
{
$this->middleware('auth');
$this->tasks = $tasks;
}

Now use forUser() inside index method.

public function index(Request $request)
{
return view('tasks.index', [
'tasks' => $this->tasks->forUser($request->user()),
]);
}

This is how a Repository can be created and implemented in Laravel Application.



Add your answer

×

Hi! Please sign in to add your answer.