🔴 Laravel Intermediate

What is the Repository Pattern in Laravel?

Why Interviewers Ask This

Mid-level Laravel roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

The Repository pattern abstracts the data access layer from business logic. Define an interface: interface PostRepositoryInterface { public function findAll(): Collection; public function findById(int $id): Post; }. Implement it: class EloquentPostRepository implements PostRepositoryInterface { public function findAll() { return Post::all(); } }. Bind in a service provider: $this->app->bind(PostRepositoryInterface::class, EloquentPostRepository::class). Inject the interface in controllers. Benefits: easy to switch data sources (swap Eloquent for an API or flat files), unit-testable (inject a mock repository), and business logic never references Eloquent directly. Laravel's tight Eloquent integration means repositories are optional — many teams skip them and use Eloquent directly, using it with service classes for complex logic.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Laravel answers easy to follow.