architecture Junior

What is the repository pattern vs Eloquent?

Short Answer

Repository pattern adds an abstraction layer over Eloquent. Eloquent itself is already a repository-like Active Record implementation.

Detailed Answer

Eloquent: - Active Record pattern: model represents both data and behavior - Direct database interaction - Built into Laravel, rich feature set - Tightly coupled to the database Repository Pattern: - Separates data access from business logic - Interface-based, swappable implementations - Easier to test (mock the interface) - Adds complexity When to use Repository: - Multiple data sources (API + database) - Complex business logic - Heavy testing requirements - Team preferences for clean architecture When Eloquent alone is fine: - Small to medium applications - Rapid prototyping - Simple CRUD operations - Team is experienced with Eloquent

Code Example

Example
// Eloquent only (simple, effective)
class PostController extends Controller
{
    public function index()
    {
        return Post::with('user')->latest()->paginate();
    }
}

// Repository pattern (more structure)
class PostController extends Controller
{
    public function __construct(
        private PostRepositoryInterface $posts
    ) {}
    
    public function index()
    {
        return $this->posts->paginated();
    }
}

// Repository implementation
class EloquentPostRepository implements PostRepositoryInterface
{
    public function paginated(int $perPage = 15): LengthAwarePaginator
    {
        return Post::with(['user', 'tags'])->latest()->paginate($perPage);
    }
}

Interview Tip

Be balanced: "Eloquent is sufficient for most applications. The repository pattern adds value when you need abstraction for testing or multiple data sources."