Laravel Code Review: Why NOT Use Repository Pattern?

Поділитися
Вставка
  • Опубліковано 20 бер 2021
  • Repository pattern is one of the most misunderstood topics in Laravel, and in this video, I will explain why.
    Also, starting TWO new experiments for code reviews!
    Repository to review: github.com/alijumaan/Laravel-...
    Want your code reviewed? Here's a Google Sheet: docs.google.com/spreadsheets/...
    My Tweet about Code Reviews Project idea (READ THE REPLIES!): / 1372838006508417026
    Repository Pattern articles (READ THE COMMENTS!):
    - laravelarticle.com/repository...
    - dev.to/asperbrothers/laravel-...
    - / whats_your_opinion_on_...
    Related videos:
    - Group Code Review: Laravel Image Upload & Resize • Group Code Review: Lar...
    - Laravel: When to Use Static Methods, Services, and Dependency Injection • Laravel: When to Use S...
    - - - - -
    Support the channel by checking out our products:
    - Try our Laravel QuickAdminPanel: bit.ly/quickadminpanel
    - Enroll in my Laravel courses: laraveldaily.teachable.com
    - Purchase my Livewire Kit: livewirekit.com
    - Subscribe to my weekly newsletter: bit.ly/laravel-newsletter
  • Навчання та стиль

КОМЕНТАРІ • 237

  • @nihadatakishiyev6881
    @nihadatakishiyev6881 3 роки тому +69

    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!

  • @michazakrzewski4199
    @michazakrzewski4199 2 роки тому +27

    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.

  • @gustavolol3
    @gustavolol3 3 роки тому +15

    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.

  • @flobbos
    @flobbos 3 роки тому +29

    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.

    • @LaravelDaily
      @LaravelDaily  3 роки тому +9

      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.

    • @jadetaboada447
      @jadetaboada447 Рік тому +1

      I have to agree to this one.

    • @itsLarryAlright
      @itsLarryAlright Рік тому

      @@LaravelDaily what about cases where a project needs both API's and blade view, should repository Pattern be used?

    • @abdelghaniabdou7578
      @abdelghaniabdou7578 Рік тому +2

      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

    • @JamesAutoDude
      @JamesAutoDude 8 місяців тому

      I would say that's more like a Job or a Service, but I understand what you're saying

  • @jopaymaymay
    @jopaymaymay 3 роки тому +40

    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 :)

    • @LaravelDaily
      @LaravelDaily  3 роки тому +41

      Not sure if "sexiest" is the title that I aimed for... :) But thanks!

    • @kvazaios5026
      @kvazaios5026 3 роки тому +6

      Your Eloquent querys hot AF

    • @jopaymaymay
      @jopaymaymay 3 роки тому +6

      @@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.

    • @mohamedshuaau632
      @mohamedshuaau632 3 роки тому

      ...

  • @AhsanKhan89
    @AhsanKhan89 Рік тому +31

    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.

    • @chrisalexthomas
      @chrisalexthomas Рік тому +4

      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

    • @noletovictor
      @noletovictor 11 місяців тому +5

      Why not use Model itself for this?

    • @Kotenarok
      @Kotenarok 6 місяців тому +1

      @@noletovictor because you have to copy /paste the codes every times you need to access data. And it's easier for unit testing.

  • @manoelbueno9997
    @manoelbueno9997 3 роки тому +1

    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.

  • @HussamAdil
    @HussamAdil 3 роки тому +1

    you really improve the Laravel community. Thanks,

  • @sean_reyes
    @sean_reyes 3 роки тому +4

    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"

  • @zoba82
    @zoba82 3 роки тому +1

    One of the most interesting videos of your channel. Thanks!

  • @pedrolucca9596
    @pedrolucca9596 3 роки тому +28

    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.

    • @MrMatni45
      @MrMatni45 2 роки тому +2

      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

    • @13karatjaws88
      @13karatjaws88 2 роки тому +1

      @@MrMatni45Hey, have you figured it out?

  • @thamibn
    @thamibn 3 роки тому +6

    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.

  • @anili632
    @anili632 3 роки тому

    How to improve my sql and eloquent skills, like using ORM's frequently with saving much time in query

  • @wijnandvanderweij5063
    @wijnandvanderweij5063 2 роки тому +5

    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.

  • @abdulgaffarabdulmalik4333
    @abdulgaffarabdulmalik4333 Рік тому

    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?

  • @HelySousaOficial
    @HelySousaOficial 3 роки тому +4

    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.

    • @LaravelDaily
      @LaravelDaily  3 роки тому +3

      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.

  • @tundeawopegba3037
    @tundeawopegba3037 3 роки тому

    Nice job. Making people's code better will help the community, so am interested in reviewing junior codes. It is a very good idea.

  • @BenRiley1804
    @BenRiley1804 3 роки тому +2

    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

  • @maquiavelotube
    @maquiavelotube 3 роки тому +5

    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.

  • @noaa9438
    @noaa9438 3 роки тому

    Always thank you! I have one question. Can I use rate limiter with Lumen also like Laravel?

    • @LaravelDaily
      @LaravelDaily  3 роки тому

      I don't actively work with Lumen, so can't advise, sorry.

  • @angelp11
    @angelp11 2 роки тому

    Thanks for all info bro, you're the better!

  • @Jurigag
    @Jurigag 3 роки тому +10

    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.

  • @freeeasyprogramming5151
    @freeeasyprogramming5151 2 роки тому

    Thank so much to help us change our skills by pointing on those tips

  •  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

  • @AhmadZaki95
    @AhmadZaki95 Рік тому

    what will happen if many of repositories uses the same interface ??
    how can i call the interface in controller ?

  • @VonBismarkOtto
    @VonBismarkOtto 3 роки тому +30

    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.

  • @RodrigoSantos-qg6xk
    @RodrigoSantos-qg6xk 3 роки тому +1

    make sense use repository in some controllers and someone else not? we can call the repository still? thanks for tips. :D

  • @awesome_urch
    @awesome_urch 2 роки тому

    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.

  • @zhgaaaaaan
    @zhgaaaaaan 3 роки тому

    How can implement micro services using laravel

  • @abdalrhmanalshafei920
    @abdalrhmanalshafei920 3 роки тому

    Can you make course for fcm real time laravel ?

  • @gurmukhsingh-uh5qo
    @gurmukhsingh-uh5qo Рік тому

    thank you for explaining about larvel repository pattern in detail.

  • @mk9834
    @mk9834 3 роки тому +1

    good content as always

  • @johnnyw525
    @johnnyw525 2 роки тому +2

    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.

  • @Laflamablanca969
    @Laflamablanca969 3 роки тому +5

    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.

  • @MrMatni45
    @MrMatni45 2 роки тому

    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)

    • @LaravelDaily
      @LaravelDaily  2 роки тому

      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.

  • @JamesShisiah
    @JamesShisiah 2 роки тому +1

    This is really great

  • @SanjayKumar-un7xf
    @SanjayKumar-un7xf 2 роки тому

    Excellent information !

  • @joshdanns9172
    @joshdanns9172 3 роки тому +1

    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
      @LaravelDaily  3 роки тому

      I don't want to make a full long video on caching, it's pretty deep. What questions do you have about it?

    • @joshdanns9172
      @joshdanns9172 3 роки тому +2

      @@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

  • @odunayoogungbure
    @odunayoogungbure 3 роки тому +5

    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
      @strides5806 3 роки тому

      Odunayo.. hello

    • @strides5806
      @strides5806 3 роки тому

      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?

    • @Skylence_
      @Skylence_ 3 роки тому +1

      @Strides there's enough on UA-cam to find after just using the right search words. There's also lynda.com and udemy.com, skillshare, etc

    • @odunayoogungbure
      @odunayoogungbure 3 роки тому

      @@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

    • @taghwomillionaireo.5543
      @taghwomillionaireo.5543 3 роки тому +2

      Creating atleast 3 files for every data layer is hell

  • @squattingnomad6298
    @squattingnomad6298 Рік тому

    How does this differ from Facade Pattern?

  • @khaledrahman433
    @khaledrahman433 2 роки тому

    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.

  • @gabrielfucci5434
    @gabrielfucci5434 2 місяці тому

    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??

  • @rakeshthapa9541
    @rakeshthapa9541 3 роки тому +3

    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.

  • @BalwantSingh-bb3ul
    @BalwantSingh-bb3ul 3 роки тому

    can you make video on Laravel service container how we can use in real project

  • @zhuanakbar9199
    @zhuanakbar9199 3 роки тому

    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

  • @bulent2435
    @bulent2435 3 роки тому +1

    Topic based code reviews 👍 sounds great. Other idea is also good but I don't think it will work. I like to be wrong.

  • @janbroda8592
    @janbroda8592 2 роки тому +6

    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.

  • @amitdev1485
    @amitdev1485 Рік тому

    very much clear from your this video...

  • @khurram4165
    @khurram4165 2 роки тому

    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.

    • @LaravelDaily
      @LaravelDaily  2 роки тому

      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.

    • @khurram4165
      @khurram4165 2 роки тому

      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

    • @LaravelDaily
      @LaravelDaily  2 роки тому

      I would probably use service for this. But again, it depends on the full code.

  • @TechWizardBoctulus
    @TechWizardBoctulus 5 місяців тому

    TOTALLY AGREE. Very clear.

  • @amrullahdev8895
    @amrullahdev8895 3 роки тому +2

    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 .

  • @Vayku
    @Vayku 3 роки тому

    Could you do the same breakdown for service(s)?

    • @LaravelDaily
      @LaravelDaily  3 роки тому +1

      If anyone gives me any repository to review with services :)

  • @AbbasMomeny
    @AbbasMomeny 3 роки тому

    please make tuts about how and when we must using the design pattern

  • @chrisalexthomas
    @chrisalexthomas Рік тому

    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?

  • @Skylence_
    @Skylence_ 3 роки тому +12

    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."

    • @LaravelDaily
      @LaravelDaily  3 роки тому +2

      Yes, exactly, that's the whole origin of this! Glad I'm not alone that "old" in Laravel :)

    • @johnp6115
      @johnp6115 3 роки тому +5

      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.

    • @JamesAutoDude
      @JamesAutoDude Рік тому

      @@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!

  • @sean_reyes
    @sean_reyes 3 роки тому

    I would love to join the community of being a reviewer.. also interested in helping out building the application for code review

  • @baseljuma158
    @baseljuma158 8 місяців тому

    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.

  • @bumblebity2902
    @bumblebity2902 3 роки тому +5

    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
      @hatsikmaroukian4111 3 роки тому +1

      Greetings ,kinda new here, why shouldnt I do queries in controllers ? Thanks for.your helpful reply

    • @bumblebity2902
      @bumblebity2902 3 роки тому +1

      @@hatsikmaroukian4111 read more about OOP and Design Pattern. My application for job was rejected because I don't follow for Example SOLID design pattern.

    • @PatrickCurl
      @PatrickCurl 3 роки тому

      @@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.

  • @user-cf5uf7vf2g
    @user-cf5uf7vf2g 3 роки тому +2

    summary: for model calling, is better stick to eloquent as your repository than introduce another not readable layer which is repository in this case.

  • @Meysam19871366
    @Meysam19871366 3 роки тому

    great my friend
    thanks

  • @williamokano
    @williamokano 3 роки тому +2

    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.

  • @Sunil-kq9bx
    @Sunil-kq9bx Рік тому

    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

  • @ajithlal1688
    @ajithlal1688 3 роки тому +1

    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

  • @jadetaboada447
    @jadetaboada447 Рік тому

    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.).

  • @jeffchan67
    @jeffchan67 3 роки тому +1

    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.

  • @yifanyes
    @yifanyes 7 місяців тому

    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

    • @LaravelDaily
      @LaravelDaily  7 місяців тому +1

      If that suits your scenario, fair enough, but I haven't seen Laravel project where it would be done to be used conveniently.

  • @kickass1179
    @kickass1179 3 роки тому

    I see you have a dev.to account. how can I find you there? would you link your dev.to account?

    • @LaravelDaily
      @LaravelDaily  3 роки тому

      I've written a few articles there, but wasn't worth it, so I didn't continue. Switched fully from writing (wherever) to UA-cam videos.

  • @vojtechschlesinger2356
    @vojtechschlesinger2356 Рік тому

    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.

  • @phuoctranngoc8749
    @phuoctranngoc8749 2 роки тому

    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.

  • @angelp11
    @angelp11 2 роки тому

    In some frameworks the ModelRepository is popularity, but, in Laravel we have the "Models".

  • @yahikkonr6350
    @yahikkonr6350 3 роки тому

    Thanks

  • @inglucifer83
    @inglucifer83 Рік тому +1

    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

    • @haingocduong5145
      @haingocduong5145 3 місяці тому

      use can use Repository in LARAVEL if your Model dont' extent Eloquent . Ok ?

  • @linkernetir
    @linkernetir Рік тому

    great. thanks

  • @seriousjan5655
    @seriousjan5655 3 роки тому +2

    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 ....

  • @ahmadrio
    @ahmadrio 3 роки тому

    terima kasih

  • @ParsclickTV
    @ParsclickTV Рік тому +1

    nice video.

  • @weeb3277
    @weeb3277 3 роки тому +1

    @6:40
    $i does not seem to be doing anything in that loop.

  • @sousajep
    @sousajep 3 роки тому

    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.

    • @LaravelDaily
      @LaravelDaily  3 роки тому

      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.

  • @hasnainabidkhanzada3754
    @hasnainabidkhanzada3754 2 роки тому

    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?

  • @ezp721
    @ezp721 3 роки тому

    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!

    • @LaravelDaily
      @LaravelDaily  3 роки тому

      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.

  • @narkocat
    @narkocat 3 роки тому

    You should use dependency injection because otherwise, classes without it become untestable.

  • @PatrickCurl
    @PatrickCurl 3 роки тому

    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!

  • @codelaravel
    @codelaravel 3 роки тому

    why we use repository in laravel project?

  • @abrahamgreyson
    @abrahamgreyson 3 роки тому

    you saved me man

  • @abelenocrodriguez
    @abelenocrodriguez 3 роки тому +1

    Then the correct ones would be Models, Controllers and Services?

    • @LaravelDaily
      @LaravelDaily  3 роки тому

      There's no "correct", but that would be my suggestion, yes.

    • @abelenocrodriguez
      @abelenocrodriguez 3 роки тому

      ​@@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.

  • @LESLEYYY0
    @LESLEYYY0 3 роки тому

    What about Service? Couldn't you just implement the logic in the Model class? It would make more sense

  • @dominik_vit
    @dominik_vit 2 роки тому

    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

  • @RaffMartinez
    @RaffMartinez 3 роки тому

    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.

    • @RaffMartinez
      @RaffMartinez 3 роки тому

      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.

  • @lordofdalords
    @lordofdalords 3 роки тому

    very great write everything in the controller ....... what a great idea lol

  • @neoish
    @neoish 2 місяці тому

    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.

  • @RodrigoMedeirosBrazil
    @RodrigoMedeirosBrazil 3 роки тому

    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 ?

    • @pedrolucca9596
      @pedrolucca9596 3 роки тому +2

      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 ...

    • @RodrigoMedeirosBrazil
      @RodrigoMedeirosBrazil 3 роки тому

      @@pedrolucca9596 Thats right! Service Pattern is a most used to handle business logic, right?

    • @taghwomillionaireo.5543
      @taghwomillionaireo.5543 3 роки тому

      @@pedrolucca9596 you get it

  • @valentin2312
    @valentin2312 2 роки тому

    We need senior code review :))

    • @LaravelDaily
      @LaravelDaily  2 роки тому

      Then suggest me senior code example :)

  • @_passby5399
    @_passby5399 3 роки тому +2

    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.

    • @LaravelDaily
      @LaravelDaily  3 роки тому +3

      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.

  • @wildfireDZ
    @wildfireDZ 3 роки тому

    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

  • @cumar8585
    @cumar8585 3 роки тому +1

    When i see array() in code I remember this good time when php 5.3 version was actual. laravel is not wordpress first of all

  • @Stoney_Eagle
    @Stoney_Eagle 3 роки тому +4

    A public spreadsheet... That won't last long 😂😂

  • @ivan.silicin
    @ivan.silicin Рік тому

    I use repository only to get data from a database, but save data is in the model.

  • @AbhinavKulshreshtha
    @AbhinavKulshreshtha 3 роки тому +1

    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.

    • @AbhinavKulshreshtha
      @AbhinavKulshreshtha 3 роки тому

      But all in all, I appreciate your efforts to create a junior-senior mentorship community.

    • @LaravelDaily
      @LaravelDaily  3 роки тому +3

      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.

    • @AbhinavKulshreshtha
      @AbhinavKulshreshtha 3 роки тому

      @@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.

  • @mohammadashrafuddinferdous8649
    @mohammadashrafuddinferdous8649 2 роки тому

    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.

    • @jadetaboada447
      @jadetaboada447 Рік тому

      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..

  • @user-te6sg9qs7d
    @user-te6sg9qs7d 3 роки тому +1

    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
      @LaravelDaily  3 роки тому

      What packages exactly are you suggesting to review?

    • @user-te6sg9qs7d
      @user-te6sg9qs7d 3 роки тому

      @@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.

    • @user-te6sg9qs7d
      @user-te6sg9qs7d 3 роки тому

      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)