🔴 Laravel Intermediate

What is the Repository Pattern in Laravel?

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.