Laravel Code from Controller into Service: The Right Way

Поділитися
Вставка
  • Опубліковано 3 лют 2025

КОМЕНТАРІ • 83

  • @kevinflorenzdaus
    @kevinflorenzdaus 4 роки тому +10

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

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

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

  • @mamdouhzaq
    @mamdouhzaq 5 років тому +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 5 років тому +3

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

  • @DaanaBanana
    @DaanaBanana 5 років тому +1

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

  • @ДавидИванов-г3ж
    @ДавидИванов-г3ж 5 років тому +21

    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 5 років тому +4

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

  • @JamesAutoDude
    @JamesAutoDude 2 роки тому +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

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

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

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

  • @conundrum
    @conundrum 5 років тому +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 5 років тому +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 5 років тому

      Thanks!

    • @umbezt
      @umbezt 5 років тому

      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.

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

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

    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  2 роки тому

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

  • @raykudjie2365
    @raykudjie2365 5 років тому +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 5 років тому +1

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

    • @PovilasKorop
      @PovilasKorop 5 років тому

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

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

    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  Рік тому

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

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

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

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

    Can I use service for pagination logic ?

  • @Krlos-n4k
    @Krlos-n4k 5 років тому +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 5 років тому +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.

  • @mahmoudghalayini
    @mahmoudghalayini 4 роки тому +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 4 роки тому +1

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

    • @mahmoudghalayini
      @mahmoudghalayini 4 роки тому

      Povilas Korop thank you

  • @trimble1902
    @trimble1902 5 років тому +3

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

    • @PovilasKorop
      @PovilasKorop 5 років тому +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 5 років тому

      Or create DTO, or use Fluent

  • @djamelbenali6883
    @djamelbenali6883 5 років тому +2

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

    • @PovilasKorop
      @PovilasKorop 5 років тому +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.

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

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

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

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

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

  • @mixalistheodoropoulos3715
    @mixalistheodoropoulos3715 5 років тому

    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 5 років тому +1

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

  • @aleksandarstevanovic5854
    @aleksandarstevanovic5854 4 роки тому +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

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

      OMFG i'm not the only one!

  • @khoroshoigra8388
    @khoroshoigra8388 4 роки тому

    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

  • @aitsidisaidhamza8054
    @aitsidisaidhamza8054 4 роки тому

    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

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

    Thanks Povilas as always!

  • @Kryoxys
    @Kryoxys 5 років тому +3

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

    • @PovilasKorop
      @PovilasKorop 5 років тому +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 5 років тому

      @@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 5 років тому +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.

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

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

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

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

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

    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?

  • @centerdevelopments3533
    @centerdevelopments3533 5 років тому +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 5 років тому +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.

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

    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.

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

    Thank You very much for Your work.

  • @genalitashweblib
    @genalitashweblib 5 років тому

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

    • @PovilasKorop
      @PovilasKorop 5 років тому +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 5 років тому

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

    • @lynnykviacheslav1841
      @lynnykviacheslav1841 5 років тому

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

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

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

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

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

  • @LeonardoMatosLopes
    @LeonardoMatosLopes 4 роки тому

    Great explanation! Thanks!

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

    Hope it was helpful? Man, that was great

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

    Thank you, Sir.

  • @Voolh
    @Voolh 5 років тому

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

    • @PovilasKorop
      @PovilasKorop 5 років тому

      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!

  • @thriftynick27
    @thriftynick27 5 років тому +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 5 років тому +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 5 років тому

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

  • @rahulk6802
    @rahulk6802 4 роки тому

    Fantastic... Great tip

  • @mist4620
    @mist4620 4 роки тому

    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 4 роки тому

      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 4 роки тому

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

  • @tomek.z
    @tomek.z 4 роки тому

    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 4 роки тому

      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: ua-cam.com/video/HadES55O4Wk/v-deo.html

  • @PavelOmelchenko
    @PavelOmelchenko 4 роки тому

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

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

    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

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

    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