Laravel Code from Controller into Service: The Right Way

Sdílet
Vložit
  • čas přidán 6. 09. 2024
  • Example of moving code from Controller to Service and no.1 mistake developers make here.
    - - - - -
    Try our QuickAdminPanel code generator: bit.ly/quickadm...
    - - - - -
    My newest online-course "Creating Laravel SaaS with Stripe/Cashier": bit.ly/laravel-...
    - - - - -
    My team is available for Laravel work, check out my Upwork profile: bit.ly/povilas-...

Komentáře • 83

  • @kevinflorenzdaus
    @kevinflorenzdaus Před 4 lety +10

    i love watching your content man .. i learn a thing or two everytime ... keep it up man ..
    i appreciate your work..

  • @mamdouhzaq
    @mamdouhzaq Před 4 lety +2

    Thanks for the video, I am using the same approach with little modification. I create a contract for the service which defines how to get, set params from its child. honestly using services is a quite fantastic.

    • @PovilasKorop
      @PovilasKorop Před 4 lety +3

      Yes your approach expands on my thought, same thing but with contracts which make it more strict.

  • @JamesAutoDude
    @JamesAutoDude Před rokem +2

    The other benefit is when you do user mocking... you can just pass a different user ID to the service and get the data

  • @DaanaBanana
    @DaanaBanana Před 4 lety +1

    thanks for the explanation! Was literally just researching how to do this correctly when you uploaded the video

  • @user-fd8ro7zo2o
    @user-fd8ro7zo2o Před 4 lety +20

    Can you make video about repository pattern and services pros vs cons? When to use them with controller etc... Good video by the way 👏

    • @PovilasKorop
      @PovilasKorop Před 4 lety +4

      I've covered it in my course - How to Structure Laravel Project: laraveldaily.teachable.com/p/how-to-structure-laravel-project

  • @_jn0298
    @_jn0298 Před 4 lety +7

    i wish i had seen all this viedeos before, my current proyect is so big already, making all those Services and cleaning all my Controllers would be so time consuming, at the end was my fault.

    • @PovilasKorop
      @PovilasKorop Před 4 lety +4

      It's never too late to start, at least for the practice for future projects. So you can start by creating ONE service and try to cleanup.

  • @aleksandarstevanovic5854
    @aleksandarstevanovic5854 Před 3 lety +1

    i noticed the error most developers do is overdoing it... if you have something simple like a blog, you have PostController that calls PostService that calls PostRepository which does only Post::all() and sends data back... its ok for large projects, when one method in controller calls more than 1 service class, but for a small one this pattern is overkill

  • @aitsidisaidhamza8054
    @aitsidisaidhamza8054 Před 3 lety

    That's Great ,I use to do that with the wrong way ... I would like to see some unit tests for a full service code plz

  • @NeuroNuggets01
    @NeuroNuggets01 Před 2 lety

    Hello Laravel Daily,
    Thank you for making people educated. I have watched you others videos as well, awesome work.
    But I was little confused when should I register Service and when should I use Service without registering ?

    • @LaravelDaily
      @LaravelDaily  Před 2 lety

      Search for "service" on my channel, I have more videos with examples, it should make it clearer for you

  • @pouyaparsaei3212
    @pouyaparsaei3212 Před 2 lety +1

    Hope it was helpful? Man, that was great

  • @bowiemtl
    @bowiemtl Před rokem

    Finally youtube recommended me the right video haha. When refactoring with services in mind I was confused where the controller and actual logic would be separated, this is a great explanation. The only other question I have is to do error handling with this design pattern. I could throw exceptions or return null but what if I want to display a toast message as well for example? I know this should only be handled by the controller but how can I granularly handle all that can go wrong with user input?

    • @LaravelDaily
      @LaravelDaily  Před rokem

      Impossible to answer in a short comment. I recommend our course about it: laraveldaily.com/course/exceptions-errors-laravel

    • @bowiemtl
      @bowiemtl Před rokem

      @@LaravelDaily Sorry, you're right. I was more or less venting my thought process. Thank you for following up though! Your resources are incredibly helpful even if it's just raising thought experiments about project requirements.

  • @amitleuva8739
    @amitleuva8739 Před 2 lety +1

    Is it a custom Service class or "Laravel Service Provider"?

  • @windigo000
    @windigo000 Před 3 lety +1

    cool one :) thx
    Q: what is more correct? instantiating service with "new" or injecting it in controller action call? for example ... index(Req $r, Service $s){ ... ? thank you

  • @mahmoudghalayini
    @mahmoudghalayini Před 4 lety +1

    Can you please give us a small video about services and how to build it and use it? Thank you for your videos

    • @PovilasKorop
      @PovilasKorop Před 4 lety +1

      This article should help: quickadminpanel.com/blog/laravel-when-to-use-dependency-injection-services-and-static-methods/

    • @mahmoudghalayini
      @mahmoudghalayini Před 4 lety

      Povilas Korop thank you

  • @trimble1902
    @trimble1902 Před 4 lety +3

    I think would be better use dependency injection into controller for receiving service instance

    • @PovilasKorop
      @PovilasKorop Před 4 lety +5

      Thanks for the comment Andrii. You're right, but for this video demo I didn't want to make it even more complicated and explain the injection for those who don't know what it is.
      I'm trying to focus on one idea/message in one video.

    • @PanoOdUa
      @PanoOdUa Před 4 lety

      Or create DTO, or use Fluent

  • @djamelbenali6883
    @djamelbenali6883 Před 4 lety +2

    why you use Transaction::with('project')->with('some relation').... you can use Transaction::with(['project', "other relations' , .....]); ?

    • @PovilasKorop
      @PovilasKorop Před 4 lety +1

      Good catch. The initial code was not written by me, it was some older demo project, so it may be optimized, like you suggested.

  • @myotoe2154
    @myotoe2154 Před 2 lety

    Thank you, Sir.

  • @Kryoxys
    @Kryoxys Před 4 lety +3

    Good video but it hurt seeing you use snake_case instead of following PSR.

    • @PovilasKorop
      @PovilasKorop Před 4 lety +1

      Hi Bill, great point, I admit it's my personal old bad habit, another reminder that I should get better at this. Probably should shoot a few videos on PSR-2 to force myself to use it, also teaching others. Thanks for the comment!

    • @Kryoxys
      @Kryoxys Před 4 lety

      @@PovilasKorop I just want to reiterate this is a great video. I hope my comment didn't come off rude, I'm just an advocate for standards.

    • @PovilasKorop
      @PovilasKorop Před 4 lety +6

      @@Kryoxys Nah, after 5 years of creating Laravel-related content, I got used to criticism, which often comes from opinionated vocal people, but in some cases, like yours, it's totally valid point and adds value to the content itself. So I'm thanking you and not upset at all.

  • @centerdevelopments3533
    @centerdevelopments3533 Před 4 lety +2

    Can you continue this topic please, what if we have some kind of big service, which has many classes and they are somehow connected to each other

    • @PovilasKorop
      @PovilasKorop Před 4 lety +1

      Part of the answers are covered in my online course "How to structure Laravel project": laraveldaily.teachable.com/p/how-to-structure-laravel-project
      But yeah, I have a few thoughts on similar videos with real-life examples.

  • @Nemnes
    @Nemnes Před 3 lety

    And it is next time your video helped me a lot! Thanks for content and your willingness to help, I really appreciate that :)

  • @alexisarcegomez8698
    @alexisarcegomez8698 Před 3 lety

    Excellent video, this is one of the few channels about laravel that I find helpful. By the way, the theme that Povilas uses looks great, does anyone know what theme is that?

  • @islandblaze007
    @islandblaze007 Před 3 lety

    Hi Povilas - can you make a video on when to use Facades in Laravel - is that a better way to implement Services? Thanks!

  • @conundrum
    @conundrum Před 4 lety +2

    Thanks for the video! I have a question: can we make the method transactionReport static and call it without creating a new instance of the class or there’re some reasons why we shouldn’t do that?

    • @PovilasKorop
      @PovilasKorop Před 4 lety +5

      In this particular case, there is no difference. But in general, getting used to static methods may be a bad practice, if in other cases you want to create object of that service class, then you won't be able to call that static method in a non-static way.
      Hard to explain in a comment, probably need a separate video on this, adding to the ToDo for content list.

    • @conundrum
      @conundrum Před 4 lety

      Thanks!

    • @umbezt
      @umbezt Před 4 lety

      In my opinion I don't see any problems with static methods or even getting used to them. As the video said we want to just modify and manipulate give data so a static method is okay for because it is stateless. Saving up on because you are not instantiating the class.

  • @giacomogaravaglia6742
    @giacomogaravaglia6742 Před 3 lety

    how about a "saveEntity" method? I mean i HAVE to pass the request, because of validation and so on. Maybe i can pass request and operation and based on operation the service have to handle a lot of stuff.

  • @markbriones4329
    @markbriones4329 Před 3 lety

    Should I just create a folder Services and a needed file on it? Or is there a artisan command to create service files?

    • @LaravelDaily
      @LaravelDaily  Před 3 lety +1

      Yes just create a file, there's no artisan command

  • @belce1982
    @belce1982 Před 3 lety

    Thanks Povilas as always!

  • @raykudjie2365
    @raykudjie2365 Před 4 lety +1

    what If the function transactionReport() depends on more than one property of $request. Wouldn't that be tedious to add all of them as parameters?

    • @taghwomillionaireo.5543
      @taghwomillionaireo.5543 Před 4 lety +1

      Was thinking about this, maybe chain different methods in your service class with the different Params

    • @PovilasKorop
      @PovilasKorop Před 4 lety

      Great question. If you feel you have too many parameters in a method, you can use this technique instead: czcams.com/video/BMHD5TPgEB0/video.html
      Or, you can pass some kind of array/object of parameters as one variable, but that would be similar to $request.

  • @khoroshoigra8388
    @khoroshoigra8388 Před 3 lety

    I may ask about the $request->paginate(). Where I should place it ? if it is on the service class or just on the controller. I'm confused about my case sir

  • @kovalus
    @kovalus Před rokem

    Thank You very much for Your work.

  • @igorleal1798
    @igorleal1798 Před 3 lety +1

    Hello Povilas,
    Thanks for your educational work on Laravel.
    Would you recommend to always (or almost always) move "computation logic" code from Controllers/Models into services classes?

    • @LaravelDaily
      @LaravelDaily  Před 3 lety +5

      No I wouldn't recommend that blindly as a rule. I would recommend whatever is more convenient to YOU in the future.
      Talk to your future self and to your team - is it more convenient to manage longer controllers or separate services?

    • @igorleal1798
      @igorleal1798 Před 3 lety

      @@LaravelDaily that’s it, I agree. Recently I am finding that my code gets much more clean if I keep DB related code into Models. Use the controllers as a dumb bridge between requests and responses and keep the “heavy duty logic” separated in services.

  • @LeonardoMatosLopes
    @LeonardoMatosLopes Před 3 lety

    Great explanation! Thanks!

  • @jamols09
    @jamols09 Před 2 lety

    Can I use service for pagination logic ?

  • @wildfireDZ
    @wildfireDZ Před 3 lety

    I used to separate logic from controller like you said (but in java spring). I noticed it was too much time consuming. Passing $request as param may be dirty but will make you gain time and lessen the code. The object is just an array after all

  • @rahulk6802
    @rahulk6802 Před 3 lety

    Fantastic... Great tip

  • @mixalistheodoropoulos3715

    hello,very helpful tutorial, let me ask you something...which vscode extension is this that shows (relations and columns and key..etc)? thanks

    • @PovilasKorop
      @PovilasKorop Před 4 lety +1

      I don't use vscode. I use PhpStorm, (almost) without any extensions.

  • @LESLEYYY0
    @LESLEYYY0 Před 3 lety

    I had a UserService, but migrating it to the User.php model. Is this bad practice or should I stick with the service?

    • @LaravelDaily
      @LaravelDaily  Před 3 lety

      There's no good or bad practice, do whatever you're comfortable with.

  • @VimKanzo
    @VimKanzo Před 2 lety

    Hello Povilas, great tutorial as always. Quick one, wanted to find out if your team is still available for a laravel project?

    • @LaravelDaily
      @LaravelDaily  Před 2 lety +1

      Sorry don't take client work anymore, focused on my content

  • @tomek.z
    @tomek.z Před 4 lety

    Your videos are great! The only problem is the code size, because sometimes it's unreadable while viewing on mobile. Here it's very hard to notice what exactly has been changed in the code. Could you, please, zoom in your editor for video recording? Thank you.

    • @PovilasKorop
      @PovilasKorop Před 4 lety

      I did already, for the newest videos in 2020. Increased font size from 14 to 26, can't go bigger because then code doesn't fit on the screen. See latest example: czcams.com/video/HadES55O4Wk/video.html

  • @thriftynick27
    @thriftynick27 Před 4 lety +1

    No wonder I was confused. I reading the docs on Service Providers. Where are the docs on Services? I don't see an Artisan command to create one. Is it a package I need to install? I'm using Laravel 5.8. Thanks!

    • @PovilasKorop
      @PovilasKorop Před 4 lety +2

      Hi, Service is just a name for any class you want, some people call them Helpers, some Classes, some Functions etc. That's why there is no official documentation, cause it's not a part of Laravel, it's just a PHP class.

    • @thriftynick27
      @thriftynick27 Před 4 lety

      @@PovilasKorop That was my suspicion. Thank you for the response. This is something I need right now for generating reports. :)

  • @Voolh
    @Voolh Před 4 lety

    Hi! Time code 4:31. I think, that you forgot to change the condition in line 19. ;)

    • @PovilasKorop
      @PovilasKorop Před 4 lety

      Yes, well spotted, I wasn't building a full *working* solution, I was just trying to show the main things that would change, missed that one, now can't re-shoot the video.
      Great to see that people actually watch the content to spot such mistakes. Thanks for the comment!

  • @mist4620
    @mist4620 Před 4 lety

    Great video, I've got a little bit of refactoring to do.
    Just wanted to point out you used a parameter in your service class (int $project_id), but in your controller you passed the whole project in.
    Nothing huge.

    • @PovilasKorop
      @PovilasKorop Před 4 lety

      No I didn't, it wouldn't work that way. I passed $request->project, which is integer, coming from the dropdown in the form. I understand that it's naming inconsistency, should be probably more clear about it in future videos.

    • @mist4620
      @mist4620 Před 4 lety

      @@PovilasKorop Ahhhh my bad! I didn't realise "$request->project" was an integer. Sorry! :)

  • @christianbaltazar9667
    @christianbaltazar9667 Před 3 lety

    What about injecting your service into the controller as an argument by the container?? That would be the very last step to become your advice and solution sustainable and even more estable

  • @genalitashweblib
    @genalitashweblib Před 4 lety

    Why don't you use static methods instead of new Obj ?

    • @PovilasKorop
      @PovilasKorop Před 4 lety +2

      I already answered below to another comment, in this case static methods are ok, but I just have a habit of not using them, will shoot another video explaining the cases why they are not the best solution.

    • @genalitashweblib
      @genalitashweblib Před 4 lety

      @@PovilasKorop , I understand. Thank you for answer.

    • @lynnykviacheslav1841
      @lynnykviacheslav1841 Před 4 lety

      Better to use DI in controller (for creating service's obj). And validation for request parameters.

  • @PavelOmelchenko
    @PavelOmelchenko Před 3 lety

    Ok but you didn’t describe how work with dependencies which used into service