Repository pattern in Laravel 5

Repository pattern in Laravel has become a very popular way of coding. When we know that our application is going to grow or specially when we are making an application which is database agnostic, repository patter helps us in development.The way it works is, we create an interface for let’s say each entity of our application and then we write our Eloquent implementation of that interface.

Once that is done, we register the interface in our App service provider and happily inject the Repository interface into our controller. Below is a diagram which will help you understand how we implement this inside Laravel.

Diagram to explain Repository pattern implementation in Laravel
Diagram to explain Repository pattern implementation in Laravel

So, in the middle is the Entity Todo. We create a Todo Repository which is our Interface. We then write the implementation of TodoRepository which is our EloquentTodo.

Now, EloquentTodo being an Eloquent implementation of the TodoRepository is injected with the TodoModel so that all the Eloquent methods are available to us inside our EloquentTodo implementation.

And finally, we inject the Interface into our Controller and happily use all the methods.