If Laravel communitity is one of the best out there nowdays, it's thanks to enthusiasts like you who is trying to make newcomers life easier. I appreciate all your efforts and wish you best of luck!
I agree that „clear” Repository Pattern is over engineering, but using Repository class as a place where we make all our actions on database (creation, simple select etc) is good thing because this methods can be used in different places and second we can easly write tests using DI and creating mocks for Repository objects.
From Brazil, thank you for the great video. Developing with Laravel, I found repository pattern to be necessary only in a few situations, where you need to build complex queries and because the key here is exactly what you said: "The Eloquent is a kind of repository itself.". For some other projects, languages and ORM this pattern should exists for great good.
I have to agree and disagree at the same time regarding your comments on the repository pattern. You are absolutely right that changing the underlying database never happens. It hasn't happened to me in the past 10 years. What does happen quite often though are code changes because clients need something added, the sorting changed or an extra relationship is needed. If that happens and I went with using Eloquent in controllers, I would have to go through the entire project to find every spot where the change needs to be applied. With a repository I just need to change it in one place. That's a real life example that I am confronted with on a regular basis. From personal experience I have to say that a bit of over-engineering in the beginning of a project saved me many headaches during the evolution of a project.
I do agree with such cases, but in my experience it's a hit-and-miss game, you basically need to "guess" what part to over-engineer, which parts are repeating, and what changes may come from the client.
you can achive that by using Services class instade off using the repository, generaly whene using repository you have to defin interfaces, and that interfaces are implemented in several repository so fi you need to change your controller, you need to change the repository class only expl interface test { function a (); } Class RepositoryTestOne implemente test { public function a (){ // do some actions } } Class RepositoryTestTow implemente test { public function a (){ // do Other actions } } class MyController (RepositoryTestOne repo){ // some line of codes repo->a(); } and in a futre whene you have to change your controlle you need to change only the Repository class MyController (RepositoryTestTow repo){ // some line of codes repo->a(); } @Flobbo Flobbster
Initially, I'd like to express my gratitude for the time and effort you're putting to share so dense information about Laravel. I would like to contribute a bit by commenting that at 7:00 the store method is passing the $request object to the Repository (it could be a service as well). From the single responsibility principle perspective, isn't it an antipattern? IMHO the $request object should be handled only in the controller and it should convert it to a PHP object ($request->validated, for instance) and pass it to the Repository. I think it happens also when the controller is dealing with accessing directly the database, such as in 5:08. My main point about using Repository Pattern is not only the question of changing your database, I do agree with you that it hardly happens and I saw this happening just once, but concentrating the logic (again, it could be a service) in one point, so imagine that your application changes the business rules to show in the index just the items related to your company (multi-tenancy) or produced by you unless you're an admin user. You should change it in a lot more places if you have such database requests spread across your controllers, especially if your application grows. I hope this can somehow contribute to the discussion.
Thanks for the valuable comment. Yes, passing a request is an antipattern, service/repository shouldn't know about request because they also could be called from Artisan command, for example. And yes, I agree with logic separation using a service.
Fully agree with you, people don't understand this pattern and it doesn't make sense to use it in Laravel with ActiveRecord(Eloquent) if you want to use repository pattern then use it with doctrine from the begging. Cause what people do is they always return an Eloquent model and they apply some filters and attributes and pagination on those Eloquent models which will break the whole application if we introduce new data source that does not return Eloquent models, even if there are test in place to avoid such trust me it will be a night mayor than anticipated, so you should know what your doing with this type of a pattern otherwise you just waisting time.
I just landed into this video. I wanted to say for you that your video is just FANTASTIC! The level of detail and all the analysis that you did to explain the efforts pros/cons of building repository is just amazing and very clear to understand. I wish the best to your youtube channel. Very valuable content here. Congrats! Im subscribing.
Benefits of the Repository Pattern: - The customer(controller) is now separated (decoupled) from the data access. Easy to write a test without side effects. Modify and extend entities before they are passed on to the consumer. A shareable abstraction resulting in less duplication of code. Improved maintainability of our application.
Exactly! You can mock the repository and return responses in your tests, without having to deal with the instance or static based interface from the model. Which is a pain in the ass when it comes to testing
Laravel seems to be always bad idea to get work with best practice of code. But anyway use repository to isolate your code from models. Becase Laravel implementation of AR provokes implicit model injection and the use of static methods. That makes your life harder in future and tends to destroy S from SOLID. So, USE repository even without interfaces (you can add interface later when you want to have more than one implementation) - that simplify future and lower you code coupling.
I have always thought the repository pattern was over engineered as well but still use it. In my case I have a redis cache layer which is bound to the repository interface. The cache layer then calls the actual repository, and this seems to work well as I can cache all parts of my data in as large or small chunks as I wish. The approach was originally implemented in the AsgardCMS project, and worth a look. Controller > Interface > Cache > Repository > Model > DB
THANK YOU! I’ve spent the last month researching repositories. My first reaction was, “isn’t Eloquent already separating the storage layer?” You can change your storage method in your app’s config, and everything will still work. When am I ever going to change this system to something Laravel can’t support? And the code just becomes harder to follow and read, not easier. It’s a case of over engineering is almost every real life project. I love SOLID principles, but they’re *principles* not *laws*. You shouldn’t be making your codebase harder to work on in pursuit of a principle for the sake of it! YAGNI is also and important principle.
I have used this pattern in some medium and bigger projects and now i feel the same, that in most cases it`s over engineering. generally people need services and not repositories in all most cases.
im curious...if we using services...should we apply to all method in controller to standardize our code or just on specific method..sry im new to this services and pattern
@@LaravelDaily What I mean is that you are a good model and inspiration in the Laravel community. Your content is in a shape that everyone needs :). Keep it up 💪💪 and thank you for the efforts. I always excited as you upload new videos here on youtube.
The issue here is that CouponRepository here should be actually the interface, not a class. Then if you want you can even use a model as implementation of it, but it allows you to easly change this implementation to something else. Also Active Record itself is kind of god class - it breaks heavily single responsibility pattern - it finds itself. Also repository shouldn't obviously accept the request. It should actually accept object of certain class, like PostRepository::store() method should accept object of class Post. Also repository is part of Infrastructure layer, Services are part of Application layer - which shouldn't contain really infrastructure layer(implementations), there should be interfaces used(Ports) to infrastructure. Also in bigger projects you want to separate actually the methods to find/get objects, like queries into separate interfaces and the repository which is used to write will only contain methods required for write(like store, and get the existing entity to update). This way you can write to one database, but read from another, and have other process which synchronizes between them.
The reply to this comment you mentioned at 11:00 sums it up perfectly on why you should be using the repository pattern regardless of whether you think you’re going to change your database or not.
I still like to use the repository pattern. Why? What if you want to change the storage engine? Like switch from Mysql to MongoDB par example. The repository pattern allows you to write methods like: findProductsByCategory of findByEmail. Ofcourse in smaller projects it seems like over engineering but in larger projects imho it adds flexibility. When you interface your repositories and use independency injection you can write decoupled code and not have a hard coded Model dependency in the controller.
although I have been using the Active Record pattern for a while now and honestly I find quite comfortable doing so, now I'm working on a company with 10 years code base and the Model classes became so bloated that the code is really hard to maintain. At first, the approach to move code to a service and leave the database code only in the model was ok, but then, is like the Product class (to use this video's example) became the database interface and the ProductService were the actual model class. I thing that in these cases, the Repository pattern is also the right fit, even more if the it is maintained by a larger team, because is easy for a new developer to know where the new code must go.
I'm coming from an Android development background. I once had to change the ORM library of an app's database from Room to SQLDelight. It was so much easy to change because the app was developed with Android's MVVM Clean architecture which used Repository pattern. I must confess that during the app's development, sticking to the Repository pattern at some point looks like over-engineering but it's so worth it at the long run. Your app would be flexible and so easy to decouple as well as make changes.
I've had discussions with fellow colleagues that the Repository Pattern is the most misused design pattern I've come across but they don't get it. I'm showing them this 🤝🏾
@@strides5806 As @Jonas mentioned, there are enough materials on youtube and you can also check out laracast.com. I think there is a laravel slack community for Nigeria but I don't know how active it is
The main purpose of this repository pattern is to have an extra-layer that would abstract away a particular Active Record ORM from the rest of the application. By doing this we: 1. have the ability to easily swap the ORM (or even the entire storage technology) 2. restrict most of our application from being able to directly manipulate the data in DB . This is especially important in applications with layered architecture, where you don't want any of the layers except Persistence to have direct access to the data in the storage. We can pass Doctrine entities across the entire application if we need to. It's not possible to do anything with data in the storage through entity's API alone because these are just plain old PHP objects. But it's possible in case we have AR-model instead (because they have methods like ::save(), ::delete() etc.).
I totally agree with let’s say 85% of your statings, in a really great video btw, thx! The 15% is about something you didn’t mention: cache. Surely, cache is often seen as “the ugly thing to avoid”, but it’s just a cliche, in my opinion. Like always, you have to know what you’re doing, caching everything is not a solution, but in some cases it can mean optimization, again, if done properly. And repositories can help a lot in this being a layer between data (DB and generally just… data) and consumer. Managing caching at this level can result in a well scalable and testable code, and here the thing to look in is not to switch from SQL to No-SQL or non relational DBs, but going from say Redis to Memcached, or DynamoDB or whatever, which has not the same impact as the db switches by far… Services could be used in repositories, I would say repositories SHOULD work with services, not exclude each other… sorry for the long comment
So when we have a simple create or update with eloquent it really seems over engineered, but when we have a complex query builder the repository pattern is still overengineering?? where should we put it??
Naming classes are so hard!! Since blade components and livewire are introduced in laravel I like to use them a lot but along with that my queries are scattered among many components So I like to create a classes, I call them repository but with no interface(please spare me) and inject these class in my components to keep my queries in one place and it even helps to maintain short term cache(static variables) and most importantly it just makes my life a lot easier.
I have only once ever been on a project where we needed to switch databases, and only because the team was young and didn't plan properly, and then at the end found out that, "No, no - we're a bank. We can't use open source MySQL here" IMHO, The repository pattern is an example of the Laravel community leaders introducing an idea, and the community simply lapping it up instead of questioning what it does & when it should be used - or not.
I like to use the repository pattern in bigger projects. It helps to keep logic that is being used in different places in one place. Also i like clean controllers
I believe I learned this pattern in the beginning at laracasts way back in the past with laravel 4.x (6 years ago?) when Jeffrey demonstrated refactoring in controllers actually. 😄 I'm most likely not the only person. "The only single purpose of controllers is to control traffic, period."
Yeah, Laracasts is where I learned the repository pattern in 2014. I've just spent the last week stripping out all of the repositories of a project that I've been working on. Repositories, in my opinion, create an unnecessary abstraction layer, that just complicate the codebase.
@@johnp6115 thank you. Some developer was pushing me to do repositories but after the first one I banged my head against a wall 😅 definitely not going to use them!
What gets me here in this video is that I had to build an application in c# and found that Repository Patterns are useful there so I started to think why didn't I need this way of development in Laravel? and I came up with the same idea of yours, in Laravel we have a build-in Repository pattern called Eloquent. At the beginning I was confused with naming things in Laravel, the repository is called Model while in .Net the model is only the data structure that is used to map data from database or JSON to c#, This is because c# is strongly typed language while PHP is not. Final thought is that PHP development are mainly meant to be simple while c# and strongly typed languages mainly depends on what you called over-engineering. At least for me when I develop in c# I always feel that I need to be over-engineered while in Laravel i don't.
Hi, Thanks for the nice video. I have Used repository pattern and used this pattern when i have to do few queries and that queries are so long to keep it in the controller example: I need to find the address with different parameter, getValidAddress, findAddressForShipping, getDefaultAddress etc . in that cases i have used this pattern and also used the services where needed like if those services need to call from different controllers also keep the controller clean. i am just sharing my experiences. BTW, your video was very informative, keep going.
3 ปีที่แล้ว
I have a question, when you have a tipical app with "students" and "teachers", you dont separate the logic from there? I mean some method for to know who is the teacher with all their courses cloused and some method to know who is the studen with the best score, you make this in the same model (Users)? I think the repository pattern is better than separate in 3 models (User, Teacher, Student). Is my opinion
In my opinion eloqunet or database queries and other business logic stuff must go in different classes. For example Controller only should what controller must do.
@@hatsikmaroukian4111 read more about OOP and Design Pattern. My application for job was rejected because I don't follow for Example SOLID design pattern.
@@bumblebity2902 Yeah, I get this but you could implement some common things in traits for the model, and then models become a repsository by extension... like having a HasTags trait that adds all the tagging polymorphic relations stuff and methods to the model, so you can use that for multiple models by just using the trait. AS I learned when I did rails the common theme was: FAT models, Skinny Controllers. I like to do something more like where I have Service classes that handle helpers like organizing or displaying data or formatting outputs from the db, or other similar things not necessarily persisting data in the db, so you can still have some separation from db / non-db actions on data related to a specific use case.. but really depends on the codebase, who's on the team, agreed upon standards, etc... a lot of times most model stuff just ends up in the model or a trait used by the model though.
I will use repository pattern when it comes to payment gateway integration. So that we can use two classes for production and local because most of the payment gateways are providing sandbox link for testing and production link for live transactions
Great video and interesting topic as always Povilas. It'd be awesome to hear your thoughts on caching too in a future video. I almost went with the repository pattern in the past simply because of caching. And the worst part is I wasn't sure if it was necessary or overkill.
@@LaravelDaily Just general tips on when to use caching in your project and best ways of implementing it without necessarily using the repository pattern. I'm asking this because I was close to using a package called zerospam/laravel-cacheable-repository in the past simply because of the caching features. To date, it's still unclear what I should cache and when to consider it in a project. Thanks
how can we use same service/repo to cater web and api behaviour...for example return redirect/view or json..or should we just separate the service(will lead to redundant code)
You can use the same service/repo but call it from different controllers - web controller and api controller, which would return different results - view or json.
In my experience, when we make many query code with eloquent or with another query with another model, the controller will fat. So it very difficult to maintain and fix bug. If you are in teamworking, it is a bad practice if not implement the repository pattern. Using repository pattern make code clean, follow the solid code (single and open closed) …. And we can implement any services different thought service container.
I think the problem with the repository given here is that it's not abstracting anything, it's just being used as a transparent wrapper around the models. I always thought the repository should be like some kind of api where you do actions and abstract away the model completely. The benefit of this is that you can mock the repository in your tests and provide responses for them without having to touch the models. But if you expose the models directly into the controller, how are you going to test this? Mock the models? I always found it hard to mock models since they're a static interface with a lot of functionality. How would you handle that situation? I think the repository here comes to your rescue. Or is there a better way to do this which lets you fully test your app and give you the same functionality? Maybe somebody has a better solution?
Didn't agree on the opinions on repository pattern you shared in the video, but you deserve the like for the efforts. Thanks! At least we learned something new.
Aren't repositories good for decouple code and reusing methods? I know, one controller. Two or tree is ok. Then five, twelve. Thirty entities ... and? And then you move coupons to different data engine and you can rebuild half of code ....
I agree that using Eloquent directly makes the code easier to read, but I don't think it's overengineering. Using static methods makes unit testing harder and makes your code highly coupled with Eloquent. For testing, you have to keep doing workarounds in order to make tests pass instead of using simple mocking. But, I agree with you that that layer shouldn't be repository but rather service.
Hi, I have a question if I want to save Data in multiple related tables. Then how to use Repository in this case or it is better to use repository in this scenario or not.
I'm against repository pattern in Laravel, in general, if you didn't follow it from the video. For your specific case, it's hard to comment or advise something without actually looking at the code structure in full.
Well it would be like that if a user is created then some of its value will be sent to other 2 tables means different table. Previously i am using Service to handle these but now i thinking about using it but its my first time with repository pattern but not sure whether its good approach to use that or not
I use an extra layer. Use a "Service" class easier to test and to use in other places. Last time I experienced something kinda similar to Repository pattern is on Spring.
I don’t know about 99.9% of the time but I also agree with the pattern being abused. I had a simple case where having a contract and not using a direct concrete implementation helped. I had to abstract the ACL package I was using for a project. I was not entirely sure if it satisfied my needs and halfway I had to change the ACL package and because I had abstracted this specific part of the application, changing it was a lot straightforward as it was not tightly integrated into my app. I think instead of focusing on the bad side of the pattern, focus more on explaining scenarios where it’s a good arrow in your quiver.
Better have some form of a forum instead of google sheet. Then you can assign badges like "volunteer mentors" to some regular seniors, have more controll over open and closed reviews and isolate discussions.
As I say, we will get to that, IF we have enough volunteer reviewers and students for review. There's no point in spending time on building a forum that would be empty.
@@LaravelDaily well count me in. I am not "your-level" expert in laravel but have worked enough in java, php, node even golang to help. I used to volunteer my time at a local coaching center. I would love to help.
I like to watch those kind of videos on the phone. Next time could you please consider the mobile audience by making the IDE font a little bigger? Thanks for share!
Where I worked there was a "desing pattern" that I never liked. I would like hear your opinion. We had this structure Controller -> Service -> Repository All the logic was in Repository and it doesn't makes any sense, why not only put all logic in controller also what is the fuction of Service it sonly job is to call repository. I think that it is not a real design pattern
Sometimes I think people do these things just cuz they can and just cuz it "seems cool". But really, who cares if it works and is readable. So my vote is keeping it either in the controller only, or maybe a service
I am actually looking into the answer of this exact thing of Controller -> Service -> Repository what I have understood so far is that (i don't know if i'm right or not) 1- controller should only handle request and response 2- if there is any extra business logic, do it inside service classes 3- you handle DB queries inside the repositories only so as an example if there is a request coming in we will first perform some business logic (e.g., calculate aggregates), prepare data etc., and send it to repository & after that repositories sole job would be to persist the data. there might be some cases where we don't need any extra logic in which case it might be fine to not use services / repositories. but if you want to keep consistency then you might follow this practice there as well. i guess it just comes down to personal preference or common practices in the project
@@LaravelDaily It seems to me quite consistent with almost 80% of the use cases, it seems to me the most logical way to deal with low to medium level projects.
Went thru the comments and it provided nice balance to the topic. Don't get fooled by a title. Repository is still useful concept, although maybe not in Laravel. But that is more mistake of Laravel and how is setup, that developer just don't know how to use it properly. As seniors we have the honor and responsibility to teach well and I do not blame anybody that didn't hire you because you are not knowing what is SOLID and dependency because you did not used repositories. I would still rather write three easy classes than one that does it all and requires so much overhead just that I can call statically User::find? This is so painful to refactor and also painful to read. It is glories to write when you can get data quickly, but in my eyes, it shows experience knowing where this would be okay and where is not. I was using Active Records for too long and it is true, for easy projects, why you would want repository? But then, as you start writing tests and there are more scopes how your code works (now you are writing domain logic and domain objects that do not care about the framework, or db, or caching, and reuse is the main thing), repository becomes useful and ActiveRecord bulky nightmare that have so much dependency and also it is just too bulky doing lot of things at once. Plus it is dirty to return models that you can just easily change and store; in a way also with a recent updates in PHP, it is just nice to have a strong types, readonly properties, because then some junior programmer will not fuck up and it is clear how the code should be used. I want to return data objects from my database, not logic objects. I agree that writing sometimes $repository->save($model) is sometimes a bitch than $model->save(), but it gives us a lot of benefits. Now my models are way more reusable. My domain logic will be always there and especially for code that will work for another 10 years, this is priceless. I do not nessesary write Interface for repositories, because I know I can write it later. This would be example of overhead that I do not have to solve now, I just need to know, that if I will need, it will be very easy to do so. Essentially I would make the ProductRepository the interface and then switch it to concrete new implementation via dependency injection. So please, if it make sense to you, use Repository and maybe start thinking little bit more framework agnostic.
Greate Content, thank you for keeping content update that very usefull to upgrade my laravel more efficient. Can i request a Clean Architechture on Laravel? It will great if you can upload this topic
Well, the original usecase for a repository was to interface with SQL commands. Nowdays, I probably would't use it in laravel, because Eloquent is doing this for you. In the video example, you they are replacing sql with different kind of database. I don't think this will happen in the real world and if it did, it would probably require major rewrite
The pain of writing a model, an interface, a repository and binding it to the service provider for every new feature is why I don’t like the repository pattern. Use services instead
IMHO, Active record pattern works but it breaks SRP. Model not ONLY keeping its relationsbips with others. It also responsible for queries in AR. So, to clarify the responsibility repository pattern is needed. It may not for a small project, ArR can be used for small one. Service layer is more related to business than technical. Using service class and repository class give clarity for single responsibility. It also a key point of building fat-free design. No fat model, no fat controller.
I don't know why people disregarded repository pattern because of AR.. I guess they don't even know what is the benefit of the repository pattern in the first place..
I think the problem here, even in the examples of "how to use the repository pattern" it the repositories are returning for example an array of the eloquent models, These repository classes always should return kind of primitive values, like arrays (records as an array, integer, string, but never class or model), so they can be abstracted. so never return ->all(). Return ->all()->toArray(), If the eloquent model is returned then the class will not be interchangeable, so no point in using the repository pattern at all. If the pattern is used correctly, then I think it is a great tool to separate controller, business, and infrastructure layers and also gives the answer to the question in the video, how do I change MySql to something else? Eloquent to Something else. Return and use primitive parameters so your repository is interchangeable and can be just replaced in app bindings, keep the interface, and change the repository.. Also, see Domain Driven Design principles.
Laravel is not made for complicated applications. It's beauty is in simple scenarios. That's why it has some antipatterns like Active Record in it's base template. Eloquent model in Laravel is an anemic model and a repository at the same time. That works great for smaller apps. I think if you want to abstract from the data access layer, you need to move away from Eloquent to some other ORM
I see where you're coming from and your solution is valid but if you throw scalability into the equation, this pattern starts violating SRP. Consider that now I have to switch from Eloquent to Doctrine, should my controller be subject to change in any way? It shouldn't even be aware of any persistence layer. Keeping good layer separation might be viewed as overengineering when it's in its early stage but the longer you work on it the more obvious it becomes why it was there in the first place.
just to be clear, I'm not disagreeing with you, I'm just looking at it from the other perspective. The question is not whether it is likely to switch from one persistence provider to another, the question is whether your code will survive that or someone will have to rewrite it. The more decoupled your code is the more reusable it is. This is something I'm personally more concerned with rather than how fast I can write it or how shorter the code is. It is actually very interesting that on one hand, Laravel makes DI so easy and on the other hand typical implementations take the shortest possible route, not taking advantage of DI made easy by Laravel.
I think this is an awesome idea, I'm curious if anybody wants to join forces maybe... you get teams of 5 devs who join forces to create micro-saas ideas and create small laravel based startups... I'm a freelancer, and I guess working solo for so long is kinda bumming me out, esp. with covid and stay-at-home would be nice to be on a team again even if a virtual one!
After having some time with Laravel i found it is great and to write a good Laravel code you need time to think + actual time to write and till now i have changed two jobs and all were like we need this Laravel project ASAP but i needed time since I am not a sort of person who writes without thinking just to get going, What's your or others say about this? How to be good Laravel developer who can bear all the pressure of completing the Laravel project ASAP?
Code review is good, but most of junior developers don't use great packages, which will help to create CRUD admin pannels easy, safety for example. What about package reviews? For me is better to have packages kit)
@@LaravelDaily that's a point. Laravel has a bunch of useful packages that I haven't come across, but they are there. And I want to see package reviews just to know that they exist, and simplify certain functionality during development. You are a senior programmer, you have seen a lot, and you can just show packages from your practice, what they do, what they are convenient for.
Working with roles and permissions in admin panel, Ready-made admin panels with CRUD implementation and multiple cropped image attachments. You made a video about Joedixon/laravel-translation, which helped me a lot, and this is an extremely strong package not only for production, but also for developing and creating translations. There are a bunch of tasks that make packages easier, and I want to know about them all)
I think i will use repository pattern in case of like report generation, where it usually a collection of data querying logic and sometimes a complex one. and i can make every steps of data fetching a function. So probably it will be like reading an English instead of a code but again this is a very niche and specific case, so yeah for simple problem i wont over engineering it
you should put the business logic in the service layer. If you want to use repositorys, it`s just do handle with data like database data or api data, but the logic how to handle with it, gona be in the service. Controllers should be used onlu to handle request`s ...
It would be great a video about tests. The only reason I implement repository pattern is for testing. But active record and repository pattern won't match. And testing against a temporary DB is strange.
Testing against a temporary DB is actually the CORRECT way of doing it: simulating all the situation and testing it in isolation from real project. Search my channel for "testing" or "phpunit", I have a few videos.
Used it in one project, now i am refactoring to remove it. Ok it's nice, very SOLID compliance but... hard to maintain, a lot of unnecessary code and in 80% of time you are just doing a simple CRUD. So i agree with you: in 99% you will not need it. "And if i change DB?". My friend you will not change it often. Rarely you do that. And probably you will change to other relational database. You will not do crazy stuff like change to nosql database, because this is insane. If you have to do it, so better recreate your app/system/site in other framework or stack. But there a case that is better to use Repository Pattern. That 1% case. For example if you have a lot of raw sql. Or if your project need to work with a range of storage (can use eiher a DB or a spreedsheet).
The repository isn't for database changing nowadays (in most cases). It is good to decoupling your DB query code from service and then easily test and cache it when you need it without touching the logic/controller layers.
No. This is so wrong. The controller should not have instructions HOW to do things but WHAT to do. I know that in MVC the Model should fulfill this role, but in Laravel it is not feasible, so you need an extra layer. You will understand when you start building really complex applications, not just recruiting tasks.
Been a Java Spring-Boot developper. I found my self too much repeating same stuff with repositories and other boilerplates. Over engineering is a serious issue
@@LaravelDaily sir your reply means a lot to me I am just a junior who is learning from your experience. Sir I have a request please if it is possible kindly make a tutorial series on advance sql and in which please demonstrate advance and tricky sql queries and also teach how to write advance complex sql queries and hoe to write sub queries how to structure them and what should be the approach to write complex sql queries and sub queries
@@LaravelDaily ok sir but try to make it if possible because we use eloquent orm because if this we some how forget sql and it's essence of software development I am learning on my own but if you create a free course it will be very good concise and beneficial for us if don't create it with raw sql please create it with query Builder thanks
If Laravel communitity is one of the best out there nowdays, it's thanks to enthusiasts like you who is trying to make newcomers life easier. I appreciate all your efforts and wish you best of luck!
I agree that „clear” Repository Pattern is over engineering, but using Repository class as a place where we make all our actions on database (creation, simple select etc) is good thing because this methods can be used in different places and second we can easly write tests using DI and creating mocks for Repository objects.
From Brazil, thank you for the great video. Developing with Laravel, I found repository pattern to be necessary only in a few situations, where you need to build complex queries and because the key here is exactly what you said: "The Eloquent is a kind of repository itself.". For some other projects, languages and ORM this pattern should exists for great good.
I have to agree and disagree at the same time regarding your comments on the repository pattern. You are absolutely right that changing the underlying database never happens. It hasn't happened to me in the past 10 years. What does happen quite often though are code changes because clients need something added, the sorting changed or an extra relationship is needed. If that happens and I went with using Eloquent in controllers, I would have to go through the entire project to find every spot where the change needs to be applied. With a repository I just need to change it in one place.
That's a real life example that I am confronted with on a regular basis. From personal experience I have to say that a bit of over-engineering in the beginning of a project saved me many headaches during the evolution of a project.
I do agree with such cases, but in my experience it's a hit-and-miss game, you basically need to "guess" what part to over-engineer, which parts are repeating, and what changes may come from the client.
I have to agree to this one.
@@LaravelDaily what about cases where a project needs both API's and blade view, should repository Pattern be used?
you can achive that by using Services class instade off using the repository, generaly whene using repository you have to defin interfaces, and that interfaces are implemented in several repository so fi you need to change your controller, you need to change the repository class only expl
interface test {
function a ();
}
Class RepositoryTestOne implemente test {
public function a (){
// do some actions
}
}
Class RepositoryTestTow implemente test {
public function a (){
// do Other actions
}
}
class MyController (RepositoryTestOne repo){
// some line of codes
repo->a();
}
and in a futre whene you have to change your controlle you need to change only the Repository
class MyController (RepositoryTestTow repo){
// some line of codes
repo->a();
}
@Flobbo Flobbster
I would say that's more like a Job or a Service, but I understand what you're saying
Initially, I'd like to express my gratitude for the time and effort you're putting to share so dense information about Laravel. I would like to contribute a bit by commenting that at 7:00 the store method is passing the $request object to the Repository (it could be a service as well). From the single responsibility principle perspective, isn't it an antipattern?
IMHO the $request object should be handled only in the controller and it should convert it to a PHP object ($request->validated, for instance) and pass it to the Repository. I think it happens also when the controller is dealing with accessing directly the database, such as in 5:08.
My main point about using Repository Pattern is not only the question of changing your database, I do agree with you that it hardly happens and I saw this happening just once, but concentrating the logic (again, it could be a service) in one point, so imagine that your application changes the business rules to show in the index just the items related to your company (multi-tenancy) or produced by you unless you're an admin user. You should change it in a lot more places if you have such database requests spread across your controllers, especially if your application grows.
I hope this can somehow contribute to the discussion.
Thanks for the valuable comment. Yes, passing a request is an antipattern, service/repository shouldn't know about request because they also could be called from Artisan command, for example.
And yes, I agree with logic separation using a service.
Fully agree with you, people don't understand this pattern and it doesn't make sense to use it in Laravel with ActiveRecord(Eloquent) if you want to use repository pattern then use it with doctrine from the begging. Cause what people do is they always return an Eloquent model and they apply some filters and attributes and pagination on those Eloquent models which will break the whole application if we introduce new data source that does not return Eloquent models, even if there are test in place to avoid such trust me it will be a night mayor than anticipated, so you should know what your doing with this type of a pattern otherwise you just waisting time.
I just landed into this video. I wanted to say for you that your video is just FANTASTIC! The level of detail and all the analysis that you did to explain the efforts pros/cons of building repository is just amazing and very clear to understand. I wish the best to your youtube channel. Very valuable content here. Congrats! Im subscribing.
Benefits of the Repository Pattern: - The customer(controller) is now separated (decoupled) from the data access.
Easy to write a test without side effects.
Modify and extend entities before they are passed on to the consumer.
A shareable abstraction resulting in less duplication of code.
Improved maintainability of our application.
Exactly! You can mock the repository and return responses in your tests, without having to deal with the instance or static based interface from the model. Which is a pain in the ass when it comes to testing
Why not use Model itself for this?
@@noletovictor because you have to copy /paste the codes every times you need to access data. And it's easier for unit testing.
Laravel seems to be always bad idea to get work with best practice of code.
But anyway use repository to isolate your code from models. Becase Laravel implementation of AR provokes implicit model injection and the use of static methods. That makes your life harder in future and tends to destroy S from SOLID.
So, USE repository even without interfaces (you can add interface later when you want to have more than one implementation) - that simplify future and lower you code coupling.
I have always thought the repository pattern was over engineered as well but still use it. In my case I have a redis cache layer which is bound to the repository interface. The cache layer then calls the actual repository, and this seems to work well as I can cache all parts of my data in as large or small chunks as I wish. The approach was originally implemented in the AsgardCMS project, and worth a look.
Controller > Interface > Cache > Repository > Model > DB
THANK YOU! I’ve spent the last month researching repositories. My first reaction was, “isn’t Eloquent already separating the storage layer?” You can change your storage method in your app’s config, and everything will still work. When am I ever going to change this system to something Laravel can’t support? And the code just becomes harder to follow and read, not easier. It’s a case of over engineering is almost every real life project. I love SOLID principles, but they’re *principles* not *laws*. You shouldn’t be making your codebase harder to work on in pursuit of a principle for the sake of it! YAGNI is also and important principle.
I have used this pattern in some medium and bigger projects and now i feel the same, that in most cases it`s over engineering. generally people need services and not repositories in all most cases.
im curious...if we using services...should we apply to all method in controller to standardize our code or just on specific method..sry im new to this services and pattern
@@MrMatni45Hey, have you figured it out?
You are one of the sexiest man in the Laravel community :) . Thank you so much for your efforts and contribution. I hope you all the best :)
Not sure if "sexiest" is the title that I aimed for... :) But thanks!
Your Eloquent querys hot AF
@@LaravelDaily What I mean is that you are a good model and inspiration in the Laravel community. Your content is in a shape that everyone needs :). Keep it up 💪💪 and thank you for the efforts. I always excited as you upload new videos here on youtube.
...
The issue here is that CouponRepository here should be actually the interface, not a class. Then if you want you can even use a model as implementation of it, but it allows you to easly change this implementation to something else.
Also Active Record itself is kind of god class - it breaks heavily single responsibility pattern - it finds itself. Also repository shouldn't obviously accept the request. It should actually accept object of certain class, like PostRepository::store() method should accept object of class Post.
Also repository is part of Infrastructure layer, Services are part of Application layer - which shouldn't contain really infrastructure layer(implementations), there should be interfaces used(Ports) to infrastructure.
Also in bigger projects you want to separate actually the methods to find/get objects, like queries into separate interfaces and the repository which is used to write will only contain methods required for write(like store, and get the existing entity to update).
This way you can write to one database, but read from another, and have other process which synchronizes between them.
The reply to this comment you mentioned at 11:00 sums it up perfectly on why you should be using the repository pattern regardless of whether you think you’re going to change your database or not.
I still like to use the repository pattern. Why? What if you want to change the storage engine? Like switch from Mysql to MongoDB par example. The repository pattern allows you to write methods like: findProductsByCategory of findByEmail. Ofcourse in smaller projects it seems like over engineering but in larger projects imho it adds flexibility. When you interface your repositories and use independency injection you can write decoupled code and not have a hard coded Model dependency in the controller.
although I have been using the Active Record pattern for a while now and honestly I find quite comfortable doing so, now I'm working on a company with 10 years code base and the Model classes became so bloated that the code is really hard to maintain. At first, the approach to move code to a service and leave the database code only in the model was ok, but then, is like the Product class (to use this video's example) became the database interface and the ProductService were the actual model class. I thing that in these cases, the Repository pattern is also the right fit, even more if the it is maintained by a larger team, because is easy for a new developer to know where the new code must go.
I'm coming from an Android development background. I once had to change the ORM library of an app's database from Room to SQLDelight. It was so much easy to change because the app was developed with Android's MVVM Clean architecture which used Repository pattern. I must confess that during the app's development, sticking to the Repository pattern at some point looks like over-engineering but it's so worth it at the long run. Your app would be flexible and so easy to decouple as well as make changes.
Would repository pattern come in handy, in cases where you need to optimize a certain query that's used in different controllers in your app?
how do you decide which topic to tackle ?
I would love to hear you talk about "Best way to handle different user roles with specific attribute"
I've had discussions with fellow colleagues that the Repository Pattern is the most misused design pattern I've come across but they don't get it. I'm showing them this 🤝🏾
Odunayo.. hello
I am based in Lagos and I know absolutely nothing about Laravel, PHP or coding in general. Is there a community for Nigerian Laravel developers?
@Strides there's enough on TH-cam to find after just using the right search words. There's also lynda.com and udemy.com, skillshare, etc
@@strides5806 As @Jonas mentioned, there are enough materials on youtube and you can also check out laracast.com. I think there is a laravel slack community for Nigeria but I don't know how active it is
Creating atleast 3 files for every data layer is hell
One of the most interesting videos of your channel. Thanks!
you really improve the Laravel community. Thanks,
Nice job. Making people's code better will help the community, so am interested in reviewing junior codes. It is a very good idea.
The main purpose of this repository pattern is to have an extra-layer that would abstract away a particular Active Record ORM from the rest of the application.
By doing this we:
1. have the ability to easily swap the ORM (or even the entire storage technology)
2. restrict most of our application from being able to directly manipulate the data in DB . This is especially important in applications with layered architecture, where you don't want any of the layers except Persistence to have direct access to the data in the storage. We can pass Doctrine entities across the entire application if we need to. It's not possible to do anything with data in the storage through entity's API alone because these are just plain old PHP objects. But it's possible in case we have AR-model instead (because they have methods like ::save(), ::delete() etc.).
Thanks for all info bro, you're the better!
thank you for explaining about larvel repository pattern in detail.
I totally agree with let’s say 85% of your statings, in a really great video btw, thx! The 15% is about something you didn’t mention: cache. Surely, cache is often seen as “the ugly thing to avoid”, but it’s just a cliche, in my opinion. Like always, you have to know what you’re doing, caching everything is not a solution, but in some cases it can mean optimization, again, if done properly. And repositories can help a lot in this being a layer between data (DB and generally just… data) and consumer. Managing caching at this level can result in a well scalable and testable code, and here the thing to look in is not to switch from SQL to No-SQL or non relational DBs, but going from say Redis to Memcached, or DynamoDB or whatever, which has not the same impact as the db switches by far… Services could be used in repositories, I would say repositories SHOULD work with services, not exclude each other… sorry for the long comment
use can use Repository in LARAVEL if your Model dont' extent Eloquent . Ok ?
So when we have a simple create or update with eloquent it really seems over engineered, but when we have a complex query builder the repository pattern is still overengineering?? where should we put it??
Naming classes are so hard!! Since blade components and livewire are introduced in laravel I like to use them a lot but along with that my queries are scattered among many components So I like to create a classes, I call them repository but with no interface(please spare me) and inject these class in my components to keep my queries in one place and it even helps to maintain short term cache(static variables) and most importantly it just makes my life a lot easier.
@6:40
$i does not seem to be doing anything in that loop.
Thank so much to help us change our skills by pointing on those tips
summary: for model calling, is better stick to eloquent as your repository than introduce another not readable layer which is repository in this case.
I have only once ever been on a project where we needed to switch databases, and only because the team was young and didn't plan properly, and then at the end found out that, "No, no - we're a bank. We can't use open source MySQL here"
IMHO, The repository pattern is an example of the Laravel community leaders introducing an idea, and the community simply lapping it up instead of questioning what it does & when it should be used - or not.
I like to use the repository pattern in bigger projects. It helps to keep logic that is being used in different places in one place. Also i like clean controllers
I believe I learned this pattern in the beginning at laracasts way back in the past with laravel 4.x (6 years ago?) when Jeffrey demonstrated refactoring in controllers actually. 😄 I'm most likely not the only person.
"The only single purpose of controllers is to control traffic, period."
Yes, exactly, that's the whole origin of this! Glad I'm not alone that "old" in Laravel :)
Yeah, Laracasts is where I learned the repository pattern in 2014.
I've just spent the last week stripping out all of the repositories of a project that I've been working on. Repositories, in my opinion, create an unnecessary abstraction layer, that just complicate the codebase.
@@johnp6115 thank you. Some developer was pushing me to do repositories but after the first one I banged my head against a wall 😅 definitely not going to use them!
what will happen if many of repositories uses the same interface ??
how can i call the interface in controller ?
What gets me here in this video is that I had to build an application in c# and found that Repository Patterns are useful there so I started to think why didn't I need this way of development in Laravel? and I came up with the same idea of yours, in Laravel we have a build-in Repository pattern called Eloquent.
At the beginning I was confused with naming things in Laravel, the repository is called Model while in .Net the model is only the data structure that is used to map data from database or JSON to c#, This is because c# is strongly typed language while PHP is not.
Final thought is that PHP development are mainly meant to be simple while c# and strongly typed languages mainly depends on what you called over-engineering. At least for me when I develop in c# I always feel that I need to be over-engineered while in Laravel i don't.
TOTALLY AGREE. Very clear.
Hi, Thanks for the nice video.
I have Used repository pattern and used this pattern when i have to do few queries and that queries are so long to keep it in the controller example:
I need to find the address with different parameter, getValidAddress, findAddressForShipping, getDefaultAddress etc . in that cases i have used this pattern and also used the services where needed like if those services need to call from different controllers also keep the controller clean. i am just sharing my experiences.
BTW, your video was very informative, keep going.
I have a question, when you have a tipical app with "students" and "teachers", you dont separate the logic from there? I mean some method for to know who is the teacher with all their courses cloused and some method to know who is the studen with the best score, you make this in the same model (Users)? I think the repository pattern is better than separate in 3 models (User, Teacher, Student). Is my opinion
In my opinion eloqunet or database queries and other business logic stuff must go in different classes. For example Controller only should what controller must do.
Greetings ,kinda new here, why shouldnt I do queries in controllers ? Thanks for.your helpful reply
@@hatsikmaroukian4111 read more about OOP and Design Pattern. My application for job was rejected because I don't follow for Example SOLID design pattern.
@@bumblebity2902 Yeah, I get this but you could implement some common things in traits for the model, and then models become a repsository by extension... like having a HasTags trait that adds all the tagging polymorphic relations stuff and methods to the model, so you can use that for multiple models by just using the trait.
AS I learned when I did rails the common theme was: FAT models, Skinny Controllers. I like to do something more like where I have Service classes that handle helpers like organizing or displaying data or formatting outputs from the db, or other similar things not necessarily persisting data in the db, so you can still have some separation from db / non-db actions on data related to a specific use case.. but really depends on the codebase, who's on the team, agreed upon standards, etc... a lot of times most model stuff just ends up in the model or a trait used by the model though.
I will use repository pattern when it comes to payment gateway integration. So that we can use two classes for production and local because most of the payment gateways are providing sandbox link for testing and production link for live transactions
It’s called a service not a repository
Great video and interesting topic as always Povilas. It'd be awesome to hear your thoughts on caching too in a future video.
I almost went with the repository pattern in the past simply because of caching. And the worst part is I wasn't sure if it was necessary or overkill.
I don't want to make a full long video on caching, it's pretty deep. What questions do you have about it?
@@LaravelDaily Just general tips on when to use caching in your project and best ways of implementing it without necessarily using the repository pattern.
I'm asking this because I was close to using a package called zerospam/laravel-cacheable-repository in the past simply because of the caching features.
To date, it's still unclear what I should cache and when to consider it in a project.
Thanks
how can we use same service/repo to cater web and api behaviour...for example return redirect/view or json..or should we just separate the service(will lead to redundant code)
You can use the same service/repo but call it from different controllers - web controller and api controller, which would return different results - view or json.
make sense use repository in some controllers and someone else not? we can call the repository still? thanks for tips. :D
In my experience, when we make many query code with eloquent or with another query with another model, the controller will fat. So it very difficult to maintain and fix bug. If you are in teamworking, it is a bad practice if not implement the repository pattern. Using repository pattern make code clean, follow the solid code (single and open closed) …. And we can implement any services different thought service container.
How to improve my sql and eloquent skills, like using ORM's frequently with saving much time in query
This is really great
Excellent information !
How does this differ from Facade Pattern?
I think the problem with the repository given here is that it's not abstracting anything, it's just being used as a transparent wrapper around the models. I always thought the repository should be like some kind of api where you do actions and abstract away the model completely. The benefit of this is that you can mock the repository in your tests and provide responses for them without having to touch the models. But if you expose the models directly into the controller, how are you going to test this? Mock the models? I always found it hard to mock models since they're a static interface with a lot of functionality. How would you handle that situation? I think the repository here comes to your rescue. Or is there a better way to do this which lets you fully test your app and give you the same functionality? Maybe somebody has a better solution?
This is realy how i do my code and yeah i call it repository so confidently 😂 . I've been so wrong all the times thanks you .
Didn't agree on the opinions on repository pattern you shared in the video, but you deserve the like for the efforts. Thanks! At least we learned something new.
If you explain it deeper on why you didn't agree, maybe someone will read your comment and change their mind. My opinion is just an opinion.
Aren't repositories good for decouple code and reusing methods? I know, one controller. Two or tree is ok. Then five, twelve. Thirty entities ... and? And then you move coupons to different data engine and you can rebuild half of code ....
I agree that using Eloquent directly makes the code easier to read, but I don't think it's overengineering. Using static methods makes unit testing harder and makes your code highly coupled with Eloquent.
For testing, you have to keep doing workarounds in order to make tests pass instead of using simple mocking.
But, I agree with you that that layer shouldn't be repository but rather service.
Hi,
I have a question if I want to save Data in multiple related tables. Then how to use Repository in this case or it is better to use repository in this scenario or not.
I'm against repository pattern in Laravel, in general, if you didn't follow it from the video. For your specific case, it's hard to comment or advise something without actually looking at the code structure in full.
Well it would be like that if a user is created then some of its value will be sent to other 2 tables means different table. Previously i am using Service to handle these but now i thinking about using it but its my first time with repository pattern but not sure whether its good approach to use that or not
I would probably use service for this. But again, it depends on the full code.
How can implement micro services using laravel
Topic based code reviews 👍 sounds great. Other idea is also good but I don't think it will work. I like to be wrong.
Always thank you! I have one question. Can I use rate limiter with Lumen also like Laravel?
I don't actively work with Lumen, so can't advise, sorry.
In some frameworks the ModelRepository is popularity, but, in Laravel we have the "Models".
very much clear from your this video...
What if you had a complex role system in your application ? You could use repositories for each role and all of them implement the same interface
If that suits your scenario, fair enough, but I haven't seen Laravel project where it would be done to be used conveniently.
I use an extra layer. Use a "Service" class easier to test and to use in other places. Last time I experienced something kinda similar to Repository pattern is on Spring.
I don’t know about 99.9% of the time but I also agree with the pattern being abused. I had a simple case where having a contract and not using a direct concrete implementation helped.
I had to abstract the ACL package I was using for a project. I was not entirely sure if it satisfied my needs and halfway I had to change the ACL package and because I had abstracted this specific part of the application, changing it was a lot straightforward as it was not tightly integrated into my app.
I think instead of focusing on the bad side of the pattern, focus more on explaining scenarios where it’s a good arrow in your quiver.
Better have some form of a forum instead of google sheet. Then you can assign badges like "volunteer mentors" to some regular seniors, have more controll over open and closed reviews and isolate discussions.
But all in all, I appreciate your efforts to create a junior-senior mentorship community.
As I say, we will get to that, IF we have enough volunteer reviewers and students for review. There's no point in spending time on building a forum that would be empty.
@@LaravelDaily well count me in. I am not "your-level" expert in laravel but have worked enough in java, php, node even golang to help. I used to volunteer my time at a local coaching center. I would love to help.
I like to watch those kind of videos on the phone. Next time could you please consider the mobile audience by making the IDE font a little bigger? Thanks for share!
I tried to experiment with bigger fonts but then longer lines of code don't fit on the screen horizontally. So that's as big as I can do.
Where I worked there was a "desing pattern" that I never liked. I would like hear your opinion.
We had this structure Controller -> Service -> Repository
All the logic was in Repository and it doesn't makes any sense, why not only put all logic in controller also what is the fuction of Service it sonly job is to call repository. I think that it is not a real design pattern
Sometimes I think people do these things just cuz they can and just cuz it "seems cool". But really, who cares if it works and is readable. So my vote is keeping it either in the controller only, or maybe a service
I am actually looking into the answer of this exact thing of Controller -> Service -> Repository
what I have understood so far is that (i don't know if i'm right or not)
1- controller should only handle request and response
2- if there is any extra business logic, do it inside service classes
3- you handle DB queries inside the repositories only
so as an example if there is a request coming in we will first perform some business logic (e.g., calculate aggregates), prepare data etc., and send it to repository & after that repositories sole job would be to persist the data.
there might be some cases where we don't need any extra logic in which case it might be fine to not use services / repositories. but if you want to keep consistency then you might follow this practice there as well. i guess it just comes down to personal preference or common practices in the project
can you make video on Laravel service container how we can use in real project
Then the correct ones would be Models, Controllers and Services?
There's no "correct", but that would be my suggestion, yes.
@@LaravelDaily It seems to me quite consistent with almost 80% of the use cases, it seems to me the most logical way to deal with low to medium level projects.
Went thru the comments and it provided nice balance to the topic. Don't get fooled by a title. Repository is still useful concept, although maybe not in Laravel. But that is more mistake of Laravel and how is setup, that developer just don't know how to use it properly.
As seniors we have the honor and responsibility to teach well and I do not blame anybody that didn't hire you because you are not knowing what is SOLID and dependency because you did not used repositories. I would still rather write three easy classes than one that does it all and requires so much overhead just that I can call statically User::find? This is so painful to refactor and also painful to read. It is glories to write when you can get data quickly, but in my eyes, it shows experience knowing where this would be okay and where is not.
I was using Active Records for too long and it is true, for easy projects, why you would want repository? But then, as you start writing tests and there are more scopes how your code works (now you are writing domain logic and domain objects that do not care about the framework, or db, or caching, and reuse is the main thing), repository becomes useful and ActiveRecord bulky nightmare that have so much dependency and also it is just too bulky doing lot of things at once. Plus it is dirty to return models that you can just easily change and store; in a way also with a recent updates in PHP, it is just nice to have a strong types, readonly properties, because then some junior programmer will not fuck up and it is clear how the code should be used. I want to return data objects from my database, not logic objects.
I agree that writing sometimes $repository->save($model) is sometimes a bitch than $model->save(), but it gives us a lot of benefits. Now my models are way more reusable. My domain logic will be always there and especially for code that will work for another 10 years, this is priceless.
I do not nessesary write Interface for repositories, because I know I can write it later. This would be example of overhead that I do not have to solve now, I just need to know, that if I will need, it will be very easy to do so. Essentially I would make the ProductRepository the interface and then switch it to concrete new implementation via dependency injection.
So please, if it make sense to you, use Repository and maybe start thinking little bit more framework agnostic.
Could you do the same breakdown for service(s)?
If anyone gives me any repository to review with services :)
A public spreadsheet... That won't last long 😂😂
please make tuts about how and when we must using the design pattern
Can you make course for fcm real time laravel ?
Greate Content, thank you for keeping content update that very usefull to upgrade my laravel more efficient.
Can i request a Clean Architechture on Laravel? It will great if you can upload this topic
Well, the original usecase for a repository was to interface with SQL commands. Nowdays, I probably would't use it in laravel, because Eloquent is doing this for you. In the video example, you they are replacing sql with different kind of database. I don't think this will happen in the real world and if it did, it would probably require major rewrite
The pain of writing a model, an interface, a repository and binding it to the service provider for every new feature is why I don’t like the repository pattern. Use services instead
IMHO, Active record pattern works but it breaks SRP. Model not ONLY keeping its relationsbips with others. It also responsible for queries in AR.
So, to clarify the responsibility repository pattern is needed. It may not for a small project, ArR can be used for small one.
Service layer is more related to business than technical.
Using service class and repository class give clarity for single responsibility. It also a key point of building fat-free design. No fat model, no fat controller.
I don't know why people disregarded repository pattern because of AR.. I guess they don't even know what is the benefit of the repository pattern in the first place..
I think the problem here, even in the examples of "how to use the repository pattern" it the repositories are returning for example an array of the eloquent models, These repository classes always should return kind of primitive values, like arrays (records as an array, integer, string, but never class or model), so they can be abstracted. so never return ->all(). Return ->all()->toArray(), If the eloquent model is returned then the class will not be interchangeable, so no point in using the repository pattern at all. If the pattern is used correctly, then I think it is a great tool to separate controller, business, and infrastructure layers and also gives the answer to the question in the video, how do I change MySql to something else? Eloquent to Something else. Return and use primitive parameters so your repository is interchangeable and can be just replaced in app bindings, keep the interface, and change the repository.. Also, see Domain Driven Design principles.
Laravel is not made for complicated applications. It's beauty is in simple scenarios. That's why it has some antipatterns like Active Record in it's base template. Eloquent model in Laravel is an anemic model and a repository at the same time. That works great for smaller apps. I think if you want to abstract from the data access layer, you need to move away from Eloquent to some other ORM
I see where you're coming from and your solution is valid but if you throw scalability into the equation, this pattern starts violating SRP. Consider that now I have to switch from Eloquent to Doctrine, should my controller be subject to change in any way? It shouldn't even be aware of any persistence layer. Keeping good layer separation might be viewed as overengineering when it's in its early stage but the longer you work on it the more obvious it becomes why it was there in the first place.
just to be clear, I'm not disagreeing with you, I'm just looking at it from the other perspective. The question is not whether it is likely to switch from one persistence provider to another, the question is whether your code will survive that or someone will have to rewrite it. The more decoupled your code is the more reusable it is. This is something I'm personally more concerned with rather than how fast I can write it or how shorter the code is. It is actually very interesting that on one hand, Laravel makes DI so easy and on the other hand typical implementations take the shortest possible route, not taking advantage of DI made easy by Laravel.
nice video.
good content as always
I think this is an awesome idea, I'm curious if anybody wants to join forces maybe... you get teams of 5 devs who join forces to create micro-saas ideas and create small laravel based startups... I'm a freelancer, and I guess working solo for so long is kinda bumming me out, esp. with covid and stay-at-home would be nice to be on a team again even if a virtual one!
why we use repository in laravel project?
After having some time with Laravel i found it is great and to write a good Laravel code you need time to think + actual time to write and till now i have changed two jobs and all were like we need this Laravel project ASAP but i needed time since I am not a sort of person who writes without thinking just to get going, What's your or others say about this? How to be good Laravel developer who can bear all the pressure of completing the Laravel project ASAP?
Code review is good, but most of junior developers don't use great packages, which will help to create CRUD admin pannels easy, safety for example.
What about package reviews? For me is better to have packages kit)
What packages exactly are you suggesting to review?
@@LaravelDaily that's a point. Laravel has a bunch of useful packages that I haven't come across, but they are there. And I want to see package reviews just to know that they exist, and simplify certain functionality during development. You are a senior programmer, you have seen a lot, and you can just show packages from your practice, what they do, what they are convenient for.
Working with roles and permissions in admin panel, Ready-made admin panels with CRUD implementation and multiple cropped image attachments. You made a video about Joedixon/laravel-translation, which helped me a lot, and this is an extremely strong package not only for production, but also for developing and creating translations. There are a bunch of tasks that make packages easier, and I want to know about them all)
I would love to join the community of being a reviewer.. also interested in helping out building the application for code review
We need senior code review :))
Then suggest me senior code example :)
I think i will use repository pattern in case of like report generation, where it usually a collection of data querying logic and sometimes a complex one. and i can make every steps of data fetching a function. So probably it will be like reading an English instead of a code
but again this is a very niche and specific case, so yeah for simple problem i wont over engineering it
In simple systems like this, repositories dont make sense. But in medium systems is good! I have a question: Where I should put business logic ?
you should put the business logic in the service layer. If you want to use repositorys, it`s just do handle with data like database data or api data, but the logic how to handle with it, gona be in the service. Controllers should be used onlu to handle request`s ...
@@pedrolucca9596 Thats right! Service Pattern is a most used to handle business logic, right?
@@pedrolucca9596 you get it
What about Service? Couldn't you just implement the logic in the Model class? It would make more sense
It would be great a video about tests. The only reason I implement repository pattern is for testing. But active record and repository pattern won't match. And testing against a temporary DB is strange.
Testing against a temporary DB is actually the CORRECT way of doing it: simulating all the situation and testing it in isolation from real project. Search my channel for "testing" or "phpunit", I have a few videos.
Used it in one project, now i am refactoring to remove it. Ok it's nice, very SOLID compliance but... hard to maintain, a lot of unnecessary code and in 80% of time you are just doing a simple CRUD. So i agree with you: in 99% you will not need it. "And if i change DB?". My friend you will not change it often. Rarely you do that. And probably you will change to other relational database. You will not do crazy stuff like change to nosql database, because this is insane. If you have to do it, so better recreate your app/system/site in other framework or stack.
But there a case that is better to use Repository Pattern. That 1% case. For example if you have a lot of raw sql. Or if your project need to work with a range of storage (can use eiher a DB or a spreedsheet).
The repository isn't for database changing nowadays (in most cases). It is good to decoupling your DB query code from service and then easily test and cache it when you need it without touching the logic/controller layers.
No. This is so wrong. The controller should not have instructions HOW to do things but WHAT to do. I know that in MVC the Model should fulfill this role, but in Laravel it is not feasible, so you need an extra layer. You will understand when you start building really complex applications, not just recruiting tasks.
You should use dependency injection because otherwise, classes without it become untestable.
Been a Java Spring-Boot developper. I found my self too much repeating same stuff with repositories and other boilerplates. Over engineering is a serious issue
What about not being consistent? If you are using repository pattern in all project so you must use it for the sake of consistently
I would disagree. In some cases, repository pattern works, in other parts of the project it doesn't.
@@LaravelDaily sir your reply means a lot to me I am just a junior who is learning from your experience.
Sir I have a request please if it is possible kindly make a tutorial series on advance sql and in which please demonstrate advance and tricky sql queries and also teach how to write advance complex sql queries and hoe to write sub queries how to structure them and what should be the approach to write complex sql queries and sub queries
I don't think that general SQL would be relevant on this channel, as majority use eloquent and don't write raw SQL
@@LaravelDaily ok sir but try to make it if possible because we use eloquent orm because if this we some how forget sql and it's essence of software development I am learning on my own but if you create a free course it will be very good concise and beneficial for us if don't create it with raw sql please create it with query Builder thanks
great my friend
thanks