What is the Repository Pattern
The Repository Pattern is a design pattern that creates an additional layer for data access, so your business logic layers do not need to interact with the database directly.
๐ท Simple Definition
๐ A Repository acts as a bridge between your application logic and the database.
Instead of writing database queries in controllers or services, you put them inside a repository class.
๐ท How It Works
Without Repository:
$users = User::where('status', 1)->get();
With Repository:
$users = $this->userRepository->getActiveUsers();
๐ The controller doesnโt care how data is fetched โ only what it gets.
๐ท Key Idea
- Controller/Service โ asks for data
- Repository โ handles query logic
- Model โ interacts with database
๐ท Structure
1. Interface (optional but recommended)
Defines methods:
interface UserRepositoryInterface {
public function getActiveUsers();
}
2. Repository Class
Implements logic:
class UserRepository implements UserRepositoryInterface {
public function getActiveUsers() {
return User::where('status', 1)->get();
}
}
3. Usage in Controller
public function __construct(UserRepositoryInterface $userRepository) {
$this->userRepository = $userRepository;
}
๐ท Real-Life Example ๐ช
Think of it like a restaurant waiter:
- You (Controller) โ place order
- Waiter (Repository) โ communicates
- Kitchen (Database) โ prepares food
๐ You donโt go to the kitchen directly.
๐ท Benefits
โ
Keeps controllers clean
โ
Centralizes database queries
โ
Easy to maintain and update
โ
Makes testing easier (can mock repository)
โ
Allows switching data source (DB โ API) easily
๐ท When to Use
โ Large or complex projects
โ When queries are reused in many places
โ When following clean architecture
โ Overkill for very small CRUD apps