Laravel Service-Repository Pattern

In this article, you’ll learn about:
• Main benefits of using Repository Pattern
• How to implement a PHP Repository Pattern in Laravel?
• We will show you how to start code and implement it in the Laravel based App.

What Important – Why we need a design pattern?

Service-Repository design pattern is clean and sustainable. The concept of repositories and services ensures that you write reusable code and helps to keep your controller as simple as possible making them more readable.

The main idea to use Repository Pattern in a Laravel application is to create a bridge between models and controllers. In other words, to decouple the hard dependencies of models from the controllers.

Repositories are usually a common wrapper for your model and the place where you would write different queries in your database. A service on the other hand is a layer for handling all your application’s logic.

Based on experience, it’s really conducive to separate the logic and the wrapper of the model especially when you’re working on team or big projects.

The use of Repository Pattern has many benefits, below is a list of the most important ones:
• It centralizes data logic or business logic and service logic.
• It gives a substitution point for the unit tests.
• Provides a flexible architecture.
• Reduces duplication of code
• A lower chance for making programming errors.

Let’s start with code and implement it in your Laravel app!

Now you know the benefits of the repository pattern in Laravel, so let’s implement them in your application! 


In the beginning, we will start with a folder structure. Laravel does not have a repository command. You have to do it manually. We should start by creating a Repositories folder into our app folder. Then add PostRepository file. So the final file structure should look like this:

We call the Post model in the constructor of our class. So the PostRepository class will look like this:


Like repository, laravel doesn’t have a service command. We should start by creating a Services folder into our app folder. Then add PostService file. So the final file structure should look like this:

We inject the PostRepository dependency into the constructor of our PostService class. Now that we are done with the repository-service setup. 

PostController -> PostService -> PostRepository

So we can use makinglogic like this in the controller:

That’s it! You have implemented a repository pattern in your app. Now you can add new repositories for the other models you are using in your application.

By Ami




tel. 06-6454-8833(平日 10:00~17:00)