Back to Blog
Lesson 3 of the Intermediate Laravel: Real-World Application Patterns course
LaravelJune 25, 20263 min read

Repository Pattern Fundamentals: Decoupling Data Access in Laravel

Learn the repository pattern to decouple your Laravel business logic from Eloquent. Master interfaces, concrete implementations, and dependency injection.

LaravelArchitectureDependency InjectionRepository PatternDesign Patternsphpbackend

Previously in this course, we discussed architecting for maintainability and implementing the service layer to keep our controllers thin. While services handle business rules, they often remain tightly coupled to Eloquent models, which can make testing and swapping storage engines difficult.

Today, we introduce the repository pattern to provide a formal layer of data access abstraction. By placing an interface between your service and your database, you ensure your application remains flexible and maintainable as it scales.

Why Use the Repository Pattern?

In a typical Laravel application, services often call methods like User::where(...) directly. While this is fast, it binds your business logic to the database schema. If you ever need to fetch data from an external API, a cache layer, or a different database type, you’d have to rewrite your services.

The repository pattern acts as a mediator. Your services talk only to an interface, and the concrete repository handles the "how" of data retrieval. This is a core concept in decoupling data access from business logic, allowing you to swap implementations without touching your domain code.

1. Defining the Repository Interface

First, create an interface that defines the contract for your data operations. This tells the rest of your application what data can be retrieved, without dictating how.

PHP
namespace App\Repositories\Interfaces;

use App\Models\Task;

interface TaskRepositoryInterface
{
    public function findById(int $id): ?Task;
    public function create(array $data): Task;
}

2. Implementing the Concrete Repository

Next, implement that interface using Eloquent. This is where your actual database queries live.

PHP
namespace App\Repositories;

use App\Models\Task;
use App\Repositories\Interfaces\TaskRepositoryInterface;

class EloquentTaskRepository implements TaskRepositoryInterface
{
    public function findById(int $id): ?Task
    {
        return Task::find($id);
    }

    public function create(array $data): Task
    {
        return Task::create($data);
    }
}

3. Injecting Repositories into Services

To use this, we bind the interface to the implementation in a Service Provider, then inject it into our service class via the constructor.

In AppServiceProvider.php:

PHP
public function register()
{
    $this->app->bind(
        \App\Repositories\Interfaces\TaskRepositoryInterface::class,
        \App\Repositories\EloquentTaskRepository::class
    );
}

In your TaskService.php:

PHP
namespace App\Services;

use App\Repositories\Interfaces\TaskRepositoryInterface;

class TaskService
{
    protected $repository;

    public function __construct(TaskRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    public function getTask(int $id)
    {
        return $this->repository->findById($id);
    }
}

Hands-on Exercise

  1. Create a ProjectRepositoryInterface with a getLatest() method.
  2. Implement it as EloquentProjectRepository.
  3. Bind the interface in AppServiceProvider.
  4. Inject this repository into a new ProjectService and call getLatest() within a controller action.

Common Pitfalls

  • Over-Engineering: Don't create a repository for every single model. Only use this pattern when you anticipate needing to switch data sources or when your query logic is complex enough to warrant extraction.
  • Leaking Eloquent: Avoid returning Builder instances from your repository. If you return a query builder, you are effectively leaking the database implementation into your service. Always execute the query (get(), first(), paginate()) within the repository.
  • Ignoring Collections: Remember that Eloquent models are powerful. Don't strip away their functionality by wrapping them in generic "DTOs" unless you have a specific requirement to be completely storage-agnostic.

Recap

By using the repository pattern, you successfully decouple your business logic from the persistence layer. You've learned to define an interface, implement it via Eloquent, and use dependency injection to provide that implementation to your services. This abstraction makes your application easier to test, maintain, and evolve.

Up next: We'll dive into Project Board Domain Modeling, where we'll define the schema and relationships that our repositories will manage.

Similar Posts