The Repository Pattern is a popular design pattern that often comes up when people talk about the creation of robust and well-structured applications. Within the Laravel Ecosystem, developers usually comes with this approach in order to clean-up the code, particularly when it comes to persistence of data.
But in most cases, simply wrapping Eloquent queries inside a Repository does not necessarily means to be an improvement. In this article, we will explore why this might be the case, and in which scenarios a Repository Implementation can actually improve a Laravel Application.
The Repository Pattern: A Quick Recap
As mentioned earlier, The Repository Pattern serves to decouple a specific data access layer from the rest of the application. Repository Interfaces act like collections of data entities, providing an abstraction over whatever database they are stored in (or whether they are stored in a database at all). The general idea is that your application should generally not be accessing databases or other data storage directly, but rather through a Repository.
The Thin Wrapper Anti-Pattern in Laravel
When it comes to Laravel, many developers, when trying to implement a Repository for the first time, fall for what is commonly known as the “Thin Wrapper”-pattern. This anti-patterns consists of creating repositories that only serve to relay method-calls from the repository interface to the Eloquent model. Here’s an example of a simple repository following the thin wrapper approach
A Common Misapplication: The Thin User Repository
// app/Repositories/UserRepository.php
namespace App\Repositories;
use App\Models\User;
class UserRepository
{
public function find(int $id): ?User
{
return User::find($id);
}
public function all(): \Illuminate\Database\Eloquent\Collection
{
return User::all();
}
public function create(array $data): User
{
return User::create($data);
}
public function update(User $user, array $data): bool
{
return $user->update($data);
}
}
And then, in a service or controller, you might use it like this:
// app/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use App\Repositories\UserRepository;
class UserController extends Controller
{
protected $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function show(int $id)
{
$user = $this->userRepository->find($id); // Instead of User::find($id)
if (!$user) {
abort(404);
}
return view('users.show', compact('user'));
}
}
Why this isn't an upgrade
As you can see, this UserRepository gives very little value. It just reiterates Eloquent's API. It adds an extra layer of indirection and does not provide any new functionality or solve a particular problem. You are still bound to the underlying query builder logic of Eloquent and you have not gained true database independence. And if you ever want to move away from Eloquent (highly unlikely in a Laravel project!), you'll still have to rewrite those repository methods extensively.
Eloquent: Powerful and Often Sufficient
Laravel's Eloquent ORM is powerful and expressive. It provides a solid Active Record implementation which abstracts away much of the database interaction details. For many, if not most common CRUD operations and even moderately complex queries, Eloquent will be more than sufficient.
Direct Eloquent Usage
// app/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use App\Models\User;
class UserController extends Controller
{
public function show(int $id)
{
// Direct Eloquent usage - clean and readable
$user = User::find($id);
if (!$user) {
abort(404);
}
return view('users.show', compact('user'));
}
public function search(string $query)
{
$users = User::where('name', 'like', "%{$query}%")
->orWhere('email', 'like', "%{$query}%")
->with('posts')
->orderBy('name')
->get();
return view('users.search', compact('users'));
}
}
As you can see, direct Eloquent is short, clean, uses all the features of the ORM. These are all reasons why the majority of Laravel applications choose to use direct Eloquent over alternative approaches.
When Does the Repository Pattern Shine?
I think the repo pattern is fine, as long as you're using it to solve an actual problem. Like if you have some business logic that Eloquent can't handle cleanly, maybe you should use repository patter in that case.
1. Complex Persistence Logic (Beyond CRUD)
If you need to do something more involved than simply fetching or storing entities — for example, if you need to perform some non-trivial logic when fetching entities — you can encapsulate that logic in the repository. For example:
normalizing values when writing or reading entities
- aggregating information from multiple tables or sources
- enforcing authorization or visibility rules when fetching entities
- implementing caching logic
- transforming data when persisting or reading
For instance, a ReportRepository may contain logic for generating an analytical report — which will require fetching information from several models and performing calculations — rather than just persisting a single entity.
2. Multiple Data Sources or Technologies
If your app needs to load the same sort of "User" object from both a database and an external API, a UserRepository interface with implementations in both eloquent and an API client would be great for abstracting away the details.
// app/Repositories/UserRepositoryInterface.php
namespace App\Repositories;
use App\Models\User;
interface UserRepositoryInterface
{
public function find(int $id): ?User;
public function save(User $user): void;
// ... other methods
}
// app/Repositories/EloquentUserRepository.php
namespace App\Repositories;
use App\Models\User;
class EloquentUserRepository implements UserRepositoryInterface
{
public function find(int $id): ?User
{
return User::find($id);
}
public function save(User $user): void
{
$user->save();
}
}
// app/Repositories/ExternalApiUserRepository.php
namespace App\Repositories;
use App\Models\User;
use Illuminate\Support\Facades\Http; // Example for API interaction
class ExternalApiUserRepository implements UserRepositoryInterface
{
public function find(int $id): ?User
{
$response = Http::get("https://api.external.com/users/{$id}");
if ($response->successful()) {
return new User($response->json());
}
return null;
}
public function save(User $user): void
{
// Logic to update user via external API
Http::put("https://api.external.com/users/{$user->id}", $user->toArray());
}
}
Here, the controller or service layer relies on the UserRepositoryInterface, which can be implemented in different ways, resolved from the Laravel service container according to our needs.
3. Encapsulation of Business Logic Related to Collections
Sometimes, the repository methods contain some logic that is applied to the collection of entities, for instance, some filtering or processing specific for this entity. For example, the ProductRepository::getAvailableProducts() method can include some internal logic for retrieving only available products, considering stock, visibility, promotions.
Beyond Repositories: Other Abstractions
Sometimes, the usual need for a repository is best served by other patterns that either more closely follow Laravel conventions or better address an alternative, more specific, need.
1. Query Objects
If you have more complex queries that you would like to refactor or make more readable you should consider using Query Objects. They allow you to encapsulate individual queries while still following Laravel's conventions of using Eloquent or the query builder. You can think of them as simply extracted, possibly complex, query builder methods that may include local scopes.
// app/Queries/UsersWithActiveSubscriptionsQuery.php
namespace App\Queries;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
class UsersWithActiveSubscriptionsQuery
{
public function __invoke(Builder $query): Builder
{
return $query->whereHas('subscriptions', function ($subQuery) {
$subQuery->where('status', 'active')
->where('ends_at', '>', now());
})->with('subscriptions');
}
}
// Usage in a controller or service
namespace App\Http\Controllers;
use App\Models\User;
use App\Queries\UsersWithActiveSubscriptionsQuery;
class SubscriptionController extends Controller
{
public function index()
{
$users = (new UsersWithActiveSubscriptionsQuery)(User::query())->get();
// Or using a local scope on the User model
// $users = User::withActiveSubscriptions()->get();
return view('subscriptions.index', compact('users'));
}
}
This keeps your domain logic clean while still using Eloquent directly.
2. Service Layers & Domain Logic
Many developers, when starting with the project, try to place all business logic in a repository. But, if a certain piece of logic is performing several actions or interacting with many objects of different domains, then there must be a service layer (or domain services, command handlers, etc.) where this logic should be placed.
For example, the logic of creating a user, sending a welcome email, and storing an audit event should be placed in the UserRegistrationService and not in the UserRepository.
// app/Services/UserRegistrationService.php
namespace App\Services;
use App\Models\User;
use App\Notifications\WelcomeEmail;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Log;
class UserRegistrationService
{
public function registerUser(array $userData): User
{
$user = User::create($userData);
Notification::send($user, new WelcomeEmail());
Log::info("User {$user->email} registered successfully.");
return $user;
}
}
// Usage in a controller
namespace App\Http\Controllers;
use App\Services\UserRegistrationService;
use Illuminate\Http\Request;
class AuthController extends Controller
{
protected $registrationService;
public function __construct(UserRegistrationService $registrationService)
{
$this->registrationService = $registrationService;
}
public function register(Request $request)
{
// ... validation ...
$user = $this->registrationService->registerUser($request->all());
return redirect()->route('dashboard')->with('success', 'Welcome!');
}
}
Making the Right Choice for Your Laravel Application
When considering applying the repository pattern in Laravel, here's my advice:
- Start Small: Go with simple Eloquent model classes. They tend to provide the best balance between readability and productivity in most cases.
- Look for Signs: Are you facing situations where you need to abstract the data source? Have you noticed that your business logic is writing too many similar-looking queries against the same database tables? Do you have to change your data layer implementation often?
- Don't Repeat Yourself: If your repository methods are essentially proxies for Eloquent methods, you're just adding extra code without benefits.
- Think about Domain-Specific Terms: When designing your repository API, focus on concepts specific to the problem domain. Instead of having a method like findWhereStatusIsActive(), think about what information the business layer may need and name your methods accordingly (getAvailableProducts()).
- Explore Other Patterns: If your queries become too complex, consider using Query Objects or database query scopes. For processing complex business logic, you may want to look into Service Layers or Command Bus patterns.
The repository pattern is one of those abstractions that can make your code as understandable as a poorly written spreadsheet if used incorrectly. By default, I wouldn't recommend introducing it in a Laravel project using Eloquent ORM unless you have a specific reason to do so. The Eloquent ORM itself provides many of the same simplifications that would otherwise come from the repository pattern.
Thank you for reading this article 😊
For any query, do not hesitate to comment 💬
-compressed.jpg)