DEV Community

loading...
Cover image for Implement CRUD with Laravel Service-Repository Pattern

Implement CRUD with Laravel Service-Repository Pattern

Saf Venture
In my blog, you will find me posting about little tips I have found while learning. It might not be much, but I know it can certainly help someone out there.
Updated on ・4 min read

Buy Me A Coffee

Why Laravel Service and Repository Pattern?

Yes, indeed, there are many ways that laravel can interpret the CRUD functionality. But I personally suggest the service-repository design pattern because it’s 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.

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.

To illustrate the repository and service, we’ll build a CRUD application.
I assume you already have laravel project installed in your local machine. If none, you may read my previous post on installing laravel project at https://dev.to/jsafe00/set-up-laravel-project-in-a-virtual-machine-with-laravel-homestead-3d4a.

For the purpose of this tutorial to emphasize the service-repository pattern, I’ll be illustrating the backend side only. You may use postman to execute.
You can download then install postman here: https://www.postman.com/downloads/

To get started, let’s set up Model, Controller and Migration by executing:

php artisan make:model Post -mcr

-m, --migration Create a new migration file for the model.
-c, --controller Create a new controller for the model.
-r, --resource Indicates if the generated controller should be a resource controller

Alt Text

Route

Alt Text

Model
Please ensure that our attributes are fillable. Update Post model like below.

Alt Text

Migration
Then, update the post migration like below then execute

php artisan migrate

Alt Text

Repository
Laravel does not have a repository command. You have to do it manually. Just create a Repositories folder then add PostRepository file and add the code below.

Alt Text

We call the Post model in the constructor of our class.

Service
Like repository, laravel doesn’t have a service command. Create a Services folder, add PostService file and add the code below.

Alt Text

We inject the PostRepository dependency into the constructor of our PostService class.

Now that we are done with the repository-service setup. Let’s proceed with creating our CRUD.

Create

PostController -> PostService -> PostRepository

https://dev-to-uploads.s3.amazonaws.com/i/7hry719tcwbt0l0zxs4p.png
Alt Text

$this->postService->savePostData($data) – this part calls the savePostData function in the post service.

In the post service, we validate the data. If there are no errors,

$this->postRepository->save($data); - we call the save function in the post repository to save the data in the database.

Alt Text
Alt Text

If there are errors, for example when we didn’t input a title, then this will be displayed when we execute in postman.

Alt Text

READ

GetAllData

https://dev-to-uploads.s3.amazonaws.com/i/zdpkcz7d7pl4kah4pvli.png
Alt Text
Alt Text
Alt Text

GetById

https://dev-to-uploads.s3.amazonaws.com/i/old8umw7apwjkvkwqb58.png
Alt Text
Alt Text

Update

https://dev-to-uploads.s3.amazonaws.com/i/uddzrcqmolhupsssrk3c.png
Alt Text
Alt Text
Alt Text

Delete

https://dev-to-uploads.s3.amazonaws.com/i/izq5dwwy2n3fy3mmy4zk.png
Alt Text
Alt Text
Alt Text

I hope by just looking at the screenshots you can already see the pattern then you can easily grasp as to why the laravel service-repository pattern is clean and sustainable. You can clone this CRUD sample at https://github.com/jsafe00/laravel-service-repository

I have created a tutorial with interface implementation on this pattern at https://josafebalili.com/posts/service-repository-pattern-v2/

Or you might check my CRUD implementation of repository pattern with Laravel 8 and Php 8 at https://github.com/jsafe00/her-running-medals-api

Everything has a pattern, you just need to notice it. This goes with the saying that everything has beauty, but not everyone sees it.

May we see beauty in everything. Beauty is in the eye of the grateful.

Alt Text

Discussion (32)

Collapse
jamols09 profile image
jamols09

Hello

This guide is really great and I am trying to follow your guideline because I found tutorials from youtube pretty hard it this one is much simplier. I would just like to ask if you're kindly able to check my repo and do some recommendations/comments since I'm really not sure where to put the logic for pagination because it has some search filters and other types. Thank you very much!

Collapse
jsf00 profile image
Saf Venture Author

Glad to hear you find this tutorial easy to understand. I like to explain things as simple as possible to convey information. And I also like to process things in a logical way. That’s why I recommend if you’ll get comfortable with the implementation here, then try the advanced tutorials for this pattern. As I still have to look a lot of things on my day to day work. I’ll try to check your repo when I have some free time. Thanks.

Collapse
jamols09 profile image
jamols09 • Edited

Hey sorry for bugging but I was wondering when following this pattern where should I put my logic for search filter because I wrote it on the repository but I'm not sure if this is the way to go.
github.com/jamols09/doc-backend/bl...

Thread Thread
jsf00 profile image
Saf Venture Author

sent you a pm

Collapse
jamols09 profile image
jamols09

Thank you very much. Whenever your time pleases repo: github.com/jamols09/doc-backend

Collapse
ostap profile image
Ostap Bregin • Edited

Why create these complications? (additional layers on top of simple Eloquent CRUD)

I don't think it's good practice in that case.

adelf.tech/2019/useless-eloquent-r...

Collapse
jsf00 profile image
Saf Venture Author • Edited

Hi,

Thanks for dropping by.

Based on my experience, Laravel service-repository pattern is conducive if you're working in a big team or big projects. It is also sustainable and easy to understand to separate the logic and the wrapper of the model. 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.

Collapse
mahdipishguy profile image
Mahdi Pishguy

i think service-repository implementation difficult than repository-pattern, do you agree?

Collapse
jsf00 profile image
Saf Venture Author • Edited

I agree with you. I think laravel repository pattern implementation is easier because you only need to add the repository. But if you're thinking on the readability and flexibility of your system, I highly recommend the service-repository pattern. Separating the logic (service) and the wrapper of the model (repository) is not hard at all.

Collapse
mahdipishguy profile image
Mahdi Pishguy

I will definitely test it

Collapse
davidjije profile image
David Jijelava

Hi.
Thank you for this clear and great post.
I was wondering about this pattern and your instructions are so helpful.
But there is one thing. I am wondering how can i write unit tests in this pattern?
Should I test Repository methods? or Service methods? Which and how?

Collapse
jsf00 profile image
Saf Venture Author

Sorry, I haven't tried that.

Collapse
lokesh7186 profile image
Lokesh Tulsani

I think the service layer is enough for the CRUD operation here and Repository is not at all required since you’re only abstracting Eloquent queries inside the repository.

Also a repository is nothing more than an adapter for a specific persistence and it should not implement any business logic nor application logic.

Collapse
jsf00 profile image
Saf Venture Author

Hi,

Thanks for sharing your input. For the purpose of showing the flow of the pattern, I’m using a simple CRUD. Separating the wrapper of the model and business logic is useful if you’re working in a big team or big projects.

Collapse
zimenkoliyailya profile image
ilya

your laravel repository is good.
Do you know about Transformer of laravel repository?
Thank you

Collapse
jsf00 profile image
Saf Venture Author • Edited

Thanks. No... but maybe this will help you
andersonandra.de/l5-repository/

Collapse
zimenkoliyailya profile image
ilya

Thank you
I am following you and want to learn from you.
good regards.

Collapse
zimenkoliyailya profile image
ilya

soory but i am using laravel8.
if you know about repository of laravel 8, please teach me.
Thank you

Thread Thread
jsf00 profile image
Saf Venture Author

maybe my sample project can help you. - github.com/jsafe00/her-running-med...

repository pattern with laravel 8 and php 8...

Thread Thread
zimenkoliyailya profile image
ilya

Hello.
Thank you very much.
Sorry but i want to communicate in chat.
You are talent.
This is my skype id:
live:.cid.55d5d2aa7799e08d
Please contact.....

Collapse
zimenkoliyailya profile image
ilya

Hello
I am Ilya
Laravel has not repository command.
This is correct?

Collapse
jsf00 profile image
Saf Venture Author

Yes. As of now, there is no artisan command for repository or service. But there are composer packages that you can install that will generate these.

Collapse
zimenkoliyailya profile image
ilya

Thank you.
then, Could you please send me composer install command for repository?
good regards

Thread Thread
jsf00 profile image
Saf Venture Author • Edited

Not sure if these will work because it always depends on your laravel version. That's why I prefer to just create it manually.

github.com/OzanKurt/Repoist - composer require ozankurt/repoist
github.com/jason-guru/laravel-make... - composer require jason-guru/laravel-make-repository --dev

Collapse
jaihari profile image
harish vagjiyani

Thanks

Collapse
sosaheri profile image
Heriberto Sosa

I will try it

Collapse
pablocamara profile image
Pablo Câmara

Thanks for this post it definitely explains things nicely and I learned from it!

Collapse
jsf00 profile image
Saf Venture Author • Edited

Happy to hear you find this helpful. :)

Collapse
sdwru profile image
sdwru

Another way to do validation is by injecting request class into controller.

laravel.com/docs/8.x/validation#cr...

Collapse
jsf00 profile image
Saf Venture Author

thanks for sharing this input.

Collapse
sagarsun21 profile image
sagar-sun21

Can you please suggest me how can I do dependency injection?

Collapse
jsf00 profile image
Saf Venture Author

I read an article here about laravel dependency injection. This might be useful for you. dev.to/carlomigueldy/getting-start...