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

To Top