Repository Design Pattern in Laravel Application

Developer Shishir
May 1 · 2 min read

One of the most popular ways for building an application using Laravel is the Repository Pattern and use of this pattern has a lots of benefits and most of the developers follow this pattern to build an application using Laravel.

Repository pattern

Repository pattern is a very helpful & commonly used design pattern where data access logic is stored. It hides the details of data access logic from business logic and keep the code cleaner and more readable. This is not mandatory to use it but we should use.

A big advantage of using this repository pattern in laravel is, In laravel you are able to inject classes automatically via class hinting.

There are a fair number of steps to complete the entire repository pattern. We’re going to cover every step here.

  1. Create Repository interface & and add the method to be implemented.
  2. Create Repository class & implement repository interface.
  3. Create Repository Service Provider & bind your repository.
  4. Let laravel know your Service Provider.
  5. Use the repository in Controller.

Creating Repository Interface with the method to be implemented

To begin with repository design pattern, we need an interface to act as a contract. So, create a file and name it . The interface looks like below:

Create Repository Class

Now, we need to create our class & implement our interface. Within the same folder, create a file and named and implement UserRepositoryInterface. It should look like this:

Create repository Service Provider & bind your repository

Create a Service Provider with command php artisan make:provider {provider name} and bind your repository in method.

[Note: Provider serve as a connector to Laravel’s IoC Container and allow us to use dependency injection to inject our repository interfaces.]

Here we made a service provider named and the provider looks like below:

Note: If you try and bind before , you will get an error. You must bind the interface first.

Let laravel know your Service Provider

To let laravel know your service provider you must add your service provider into your file.

Using Repository in a Controller

Now it’s time to use our repository. The place to use this is our controller. Let’s make a controller and name it. If you use some other controller, that is fine too. The Controller looks like below:

Notice that, this controller injects Interface rather than the repository. So, this results in loosely coupled with the Product model and is more easily testable.

More than one Repository?

So, you need to create another repository. then create an interface and create the repository. Then, bind that repository in file.

Be sure to give claps if you find this article helpful. Happy Coding :)

Developer Shishir

Written by

{ 'designation' : 'Software Developer' , 'hobby' : [ 'Music', 'Photography', 'Travelling' ] ,’email’: ‘’ }