DEV Community

Cover image for The best Laravel repositories solution in 30 lines of code

The best Laravel repositories solution in 30 lines of code

Sjors van Dongen on September 13, 2019

How a 30 lines piece of script can finally provide a good solution for a repository pattern in Laravel apps. The problem Lara...
Collapse
 
mratiebatie profile image
Sjors van Dongen

I’m not sure power is the right word for this. I agree that your code will be better separated when you don’t use eloquent in combination with a repository but I’ve tried a couple repository packages for Laravel which all provide some methods for basic usage. The amount of code I had to write for the options I wanted was too much for me and more of a disadvantage than advantage. Eloquent is such a great tool and it felt like I abandoned it. That’s why I came up with this.

Collapse
 
dj_syclone profile image
Dj Syclone

If you are mostly interested in creating custom functions to attach to your Models then you could just use scopes. E.g. laravel.com/docs/5.8/eloquent#loca...

Collapse
 
mratiebatie profile image
Sjors van Dongen

Scopes are a good way to create custom query functions indeed. Still, I don't think this should be part of an instance of a Product entity though. When an instance of a Product has a method called 'findByName' it is in the wrong place in my opinion.

Collapse
 
miguelf11 profile image
Miguel Figueira • Edited

This is awesome, thanks for sharing!

But I have a doubt, How you define scopes in the repository?
Or how to reuse some queries to emulate the use of scopes, I want to define this scopes inside the repository :)

Collapse
 
mratiebatie profile image
Sjors van Dongen

Thanks for your positive comment :) Unfortunately, it's currently not possible to put your scopes in your repositories. What you could do for now is put your scopes in a separate trait and include them in your model.