Laravel Controller Code: Move to Model, Service, Action or Job?

  Рет қаралды 103,835

Laravel Daily

Laravel Daily

2 жыл бұрын

This is probably the no.1 debate in the Laravel community - "where should I put this code". Let me explain my philosophy, based on a practical example.
Original Tweet: / 1480128471032643596
Code repository: github.com/LaravelDaily/Larav...
Laravel Code Review: Why NOT Use Repository Pattern? • Laravel Code Review: W...
Laravel Services and Repositories: 3 Example Projects • Laravel Services and R...
- - - - -
Support the channel by checking out my products:
- My Laravel courses: laraveldaily.com/courses?mtm_...
- Laravel QuickAdminPanel: quickadminpanel.com
- Livewire Kit Components: livewirekit.com
- - - - -
Other places to follow:
- My weekly Laravel newsletter: us11.campaign-archive.com/hom...
- My personal Twitter: / povilaskorop

Пікірлер: 243
@gdogmalone
@gdogmalone 2 жыл бұрын
It’s uncanny how often I’m thinking about a subject in laravel (that I could work more on) and you release a video on that very subject! Thanks as ever Povilas. 👏
@gtsmeg3474
@gtsmeg3474 2 жыл бұрын
I do always create a directory called "Services" on each module of the application where lands the logic used by the controllers, so in my controllers I just pass The service class name as an argument to the controller method, and then I just call the service methof from the controller, my controller now all contains max 2 lines of code. My models contain only relationships, some overriding functions, and accessors/mutators. I can say this is a good practice
@marcgriebenow4362
@marcgriebenow4362 2 жыл бұрын
We named this directory "managers", because our "Manager" Classes don't provide real services... Lets say we have Ticket model with TicketController... The TicketManager class "manages" everything that is related to tickets. Also, the word "Service" is already claimed by Laravel core at some places... But I think the approach, independently from naming, is good :)
@cellocarlos
@cellocarlos 2 жыл бұрын
I totally agree. I also usually make the services methods as static to keep it even simple, so you don't have to instantiate it or use dependency injection
@nafischonchol
@nafischonchol Жыл бұрын
We can use interface
@BillClinton228
@BillClinton228 7 ай бұрын
No, you're doing it wrong, you need more abstractions... create another folder inside services called servicing_service, then create another folder inside that called bottle_service then add another folder inside that called micro_service, so pass data through each class to make things simpler and easier to read. The more layers of abstractions you add the simpler your code will be... flawless logic every time.
@joaquinvergara4699
@joaquinvergara4699 6 ай бұрын
@@BillClinton228 no, just throw all logic to the views
@beatnu187
@beatnu187 2 жыл бұрын
Well, that's what I mean with a clear understanding of where what belongs. Thank you for this video, makes a lot more sense now. The Service Class looks the most readable for me. You explain things so well, that I understand things that I do even not understand after reading multiple times. Another big thank you for that! Crystal Clear
@raminsadeghnasab9310
@raminsadeghnasab9310 2 жыл бұрын
Your videos are great, I can't even miss one second of them. Thanks for such a high quality content.
@mikhart
@mikhart 2 жыл бұрын
Perfect! I've just seen the preview of this video and I absolutely sure that I will use this in my job! Thanks a lot!
@adammenczykowski
@adammenczykowski 2 жыл бұрын
Totally agree with your preference of using Service classes! Love the high level comparison of ‘Model’ and ‘Service’!
@DeividasDkvadratu
@DeividasDkvadratu 2 жыл бұрын
Right on time. Few days ago I was structuring project functionality which can take some time: parse json, download files (~50mb), store them, update db. And I decided Jobs + Queue + Cron. After your video I'm staying with same decision. Thanks for content and QAP :)
@erstevn
@erstevn Жыл бұрын
Man, such a quality content. I just watch another video of using repository pattern for Laravel application and then I found this, great content brother
@adarshchacko6137
@adarshchacko6137 2 жыл бұрын
Clicked on the LIKE button the moment he started talking about the topic because this was something that always troubled me. Looking forward to more of such videos.
@eleftrik
@eleftrik 2 жыл бұрын
In my opinion, "move to model" is never an option, even for small projects. It's not models' responsibility to handle business logic and they should stay anemic. Services usually are the answer, but sometimes a service class handles too many responsibilities and methods. Better to use an action, which will handle a single aspect of the application, optionally injecting other services (each of one handling a specific responsibility).
@Samuel.Tedesque
@Samuel.Tedesque 11 ай бұрын
Thanks a lot Povilas, I was trying to understand a way to separate the logic from my model Class to a Service class and your vídeo really helped me to get it. Thks for sharing
@Coogle007
@Coogle007 2 жыл бұрын
Very nice video, totally agree as architect to this solution. Another way is to use a more comprehensive architecture pattern like the hexagonal or clean architecture, it seems difficult to apply that patterns to laravel but is just a meaning of proper layer separation, with that architectures you will end up with a usecase in this particular video scenario with all the concerns and boundaries moved to the laravel/infrastructure layer. But can be overwhelmed for small projects. Anyway I really appreciate that video, can be a light in the dark for many developers, kudos from Italy!
@gaofan2856
@gaofan2856 2 жыл бұрын
Thank you very much for such a clear explanation as always. Thanks to your videos I successfully passed my job interview for Laravel developer position, and explained things related to Laravel even made interviewer suprise :D
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Great to hear!
@thraxxdv
@thraxxdv 2 жыл бұрын
I saw you retweet this subject on Twitter. Thank you for making a video about it!
@denjand
@denjand 2 жыл бұрын
I am quite new to Laravel and this video gives me good knowledge about Laravel. Thank you very much
@rihulfaakbar2261
@rihulfaakbar2261 2 жыл бұрын
I always doing my logic in controller, but after watching this video I'm going to refactoring my controllers. Thanks for the insight 👍
@chlouis-girardot
@chlouis-girardot 2 жыл бұрын
Thank you Sir ! This topic is clearer to me now 👍
@jtovarto
@jtovarto 2 жыл бұрын
I agree with your opinion, I think it's easier to maintain a class of services than a whole model overloaded with various types of actions. A possible solution to "fatten" the model with a large number of actions is to segment them into traits according to their relationship with each other, this makes management and maintenance easier, but there will always be the risk of breaking our model. Making any changes to it could affect the performance of the model and affect our app. Great job my friend, thanks for sharing your knowledge with us every day, cheers!
@hamidimomov232
@hamidimomov232 2 жыл бұрын
Thank you for the info about the Repository pattern.
@SergiuSavva
@SergiuSavva 2 жыл бұрын
Thanks for video I have a project with complex business logic and long-run jobs. I'm dispatching Events from Controller. EventServiceProvider class stores the mapping between Listeners and Event (shouldDiscoverEvents = false) where one Event can have multiple Listeners. Job and Listener can be queueable (async) and run in the background. Inside the controller, I'm validating the Request data, creating/updating the model, and then dispatching the Event. Contoller -> Event -> Listener(s) -> Service(s) Contoller -> Event -> Listener(s) -> Service(s) -> Job(s) Contoller -> Event -> Listener(s) -> Job(s) -> Service(s)
@IlPandax
@IlPandax 2 жыл бұрын
Perfect video! In this case I would have used a service. TO ME, actions does not return anything. You perfom an action and go back. Services could return something. In this case an invoice is returned so I would have used a servece. IMHO, of course. :D
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Yes, IMHO is the most appropriate word (abbreviation) for this video and comments. And yes, after editing the video I thought about it, that I used Action maybe in not the most intended way - many people use Actions without returns, just as Jobs.
@codokit
@codokit 4 ай бұрын
Nice and useful videos. Thanks for your hard work!
@br0mley597
@br0mley597 2 жыл бұрын
I also do like to use Services, i don't know why ppl go with rep pattern for small projects or push methods in model... As you said and i completely agree, model should consist of relations, fields, casts and scopes, all model related stuff...
@jomonjohnson735
@jomonjohnson735 2 жыл бұрын
all programmers confusing this part after learning the basics. they are going to code in the way showing in docs. For small projects its OK. but for large or medium scale projects will be get more complex, hard to maintain In My point of view Models are not business logic, it represents database table. It is a gateway between application and database WebController, Console Commands, Graphql Mutator, Graphql Query Resolvers, API controllers are receive input and output processed data, Not doing any operations itself. it controls everything between visible input and visible output Actions Responsible for one specific operations assigned. action may call another action to execute. Same action can use inside WebController, Console Commands, Graphql Mutator, Graphql Query Resolvers ... etc I prefer Actions over Services to execute operations It can be Queable Services Performing computations over arguments and return its result ..etc Key point is Split Responsibilities if it going to complex. It will help for maintenance, code reusing and unit testing
@mohammadhoseinkhodnama7388
@mohammadhoseinkhodnama7388 2 жыл бұрын
I was looking for this video, fortunately it found me itself 😍
@TheMarcelitto
@TheMarcelitto 2 жыл бұрын
Just the perfect explination for this topic, thank you!
@poplach
@poplach 2 жыл бұрын
Very good, some non-junior stuff at last. Thank you.
@user-mq2xm4rq2p
@user-mq2xm4rq2p 6 ай бұрын
I am writing all the logic in the controller, now i will follow your code structure. Its good to breakdown code.
@jorgeluisbou-saad7643
@jorgeluisbou-saad7643 3 ай бұрын
It`s very interesting. I like Service too. I have been working with Angular for years and it has the same phylosophy respect with the actions. Usually I use just the methods controller for the logic but if the application is complex, have a long functions and code, it`s good idea sepatarate the logic in other class like Service. I think the same about models is for Eloquents operations...just that. Services it`s good idea for operations like actions. Jobs it`s for especific cases, for when you have to use a queue in a background.
@JustMillIt23
@JustMillIt23 Жыл бұрын
This is over my head. I wish I understood more what you are talking about, but it looks way advanced.
@CharlesM123
@CharlesM123 Жыл бұрын
Great video. Thanks Povilas.
@viniciusalvess
@viniciusalvess 25 күн бұрын
For my projects I try to keep it simple and store the "service" methods on the model file. I find it easier this way. If it is a third party project, I follow whatever convention they have stablished.
@OlexaFPV
@OlexaFPV Жыл бұрын
Thanks! Very useful
@PathOfDamn
@PathOfDamn 2 жыл бұрын
I personally use Controllers to determine the http code that is returned based on result of a service. I use service for actions that write/update the model, and declare functions in models when I want to read specific data with different conditions in said model.
@AhsanKhan89
@AhsanKhan89 Жыл бұрын
Tip: *Use the Command pattern when you want to queue operations, schedule their execution, or execute them remotely.*
@kingstalker
@kingstalker 2 жыл бұрын
Nice video Thank you
@FISS007
@FISS007 2 жыл бұрын
I totally agree with you. Model is a data container, it shoulden't contain behavior. Of corse it can host data related methods but not behavior ones.
@mahmoudnoufal9276
@mahmoudnoufal9276 10 ай бұрын
Thank you so much,
@Babaknouri
@Babaknouri Жыл бұрын
Very good explanation ✔️✔️
@izboli
@izboli Жыл бұрын
Thanks!
@devMoemen
@devMoemen Жыл бұрын
Thanks very nice.
@thisisthelogic
@thisisthelogic 2 жыл бұрын
I totally agree with you!
@jimbuot4283
@jimbuot4283 2 жыл бұрын
I have something observation regarding on using Job with dispatchSync which definitely decrease the execution time of process about 40% instead of puting my logic plainly on controller.
@EduardR10
@EduardR10 2 жыл бұрын
Gracias, profesor :)
@ivalinvenkov8208
@ivalinvenkov8208 2 жыл бұрын
I need to agree with Povilas on this one. I have been working on a project where all the logic and methods where put in the model and now the model is 500+ lines of code. It's hard for debugging and it's a mess if want check how something works.
@QueeeeenZ
@QueeeeenZ 2 жыл бұрын
@Ivalin, how do you avoid a service class from becoming 500+ lines of code? I mean if you just move all the methods from a Model to a Service class - what's the difference?
@ivalinvenkov8208
@ivalinvenkov8208 2 жыл бұрын
@@QueeeeenZ With some refactoring, in general I like the idea of structuring your code this way.
@AbdallahAjlouni
@AbdallahAjlouni 2 жыл бұрын
@@QueeeeenZ This is a good question.
@ioshaven436
@ioshaven436 2 жыл бұрын
I create a “packages” folder and create local service providers in that folder. Each service provider package is a git submodule and linked as a composer repository of type “path”. This allows me to go crazy on OOP and only publish what is necessary to my app. It also allows me to reuse services across projects.
@syamjulio3685
@syamjulio3685 2 жыл бұрын
This sounds interesting. Do you have tutorial about it? I want to read it further. Thanks.
@AlirezaSalehi-xz3ch
@AlirezaSalehi-xz3ch 2 жыл бұрын
very useful channel
@cardboarddignity
@cardboarddignity 2 жыл бұрын
According to SRP, Model should not be responsible for anything except data structure. For me, it is better to implement Repository pattern, since I consider Services as classes that stores Controller logic (kinda helpers), but Repositories always contain logic to manipulate or access data from the model
@JorgeShimadaBrn
@JorgeShimadaBrn Жыл бұрын
Thanks for sharing this information, very good video. I agree with you in keeping the business rules into a service or action. I couldn't understand one point: if you need to pass the object $orderService as a parameter to the function in the controller, how do you do this in the route or even in the blade side to send it? Thanks in advance
@moauyameghari
@moauyameghari 2 жыл бұрын
I do the same about seperate the logic from controller to another class, I create a class called InvoiceManager instead of InvoiceService, then I use the same functions from that InvoiceManager class for api and web controllers.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
So yes, it's a service class, just called differently, all good!
@slimaniyoucef2530
@slimaniyoucef2530 2 жыл бұрын
Personally, if i go from Service to Action, it's for complexity reasons ! I mean, if you've got a Service class with over 1000 lines of code, then refactoring it into a set of Action classes is not a bad idea.
@abdmaster
@abdmaster 2 жыл бұрын
Nice video. I personally use the name service as means to connection with other external services using guzzle, sftp, grpc etc. I use the name Task (alternative to Action) to separate large logic. Just my personal choice.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Yup, it's all a personal choice! It may make the difference only if you work in the team, and then your teammates need to understand that naming.
@MainTeMereDost
@MainTeMereDost 2 жыл бұрын
What if contain my logic inside a trait.an use it in my controller.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
If that trait is repeatable in at least a few other classes, then sure.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Want more? My Laravel courses membership: laraveldaily.com/courses
@user-ne8cm9ch8j
@user-ne8cm9ch8j Жыл бұрын
I wish every english speaker talked like you, I can perfectly understand every word!
@vuenice
@vuenice Ай бұрын
My proposal would be to create helper classes which extends model class, and use services for code that can be used in different projects like TwillioService, StripeService, DownloadPdfService etc
@GergelyCsermely
@GergelyCsermely 2 жыл бұрын
Thanks
@hoomanmirghasemi5773
@hoomanmirghasemi5773 2 жыл бұрын
Thanks for your video. Your service class is like Reposetory Design pattern. So it is better to rename it and move to reposetory directory and also making interface and ....
@user-mi7vo6mz1n
@user-mi7vo6mz1n 11 ай бұрын
If we follow the SOLID principle then we know that ‘S’ stands for Single Responsibility which means that a class should only be responsible for what it is for. It should never be responsible for any other related actions. In this example: Order class should only be responsible for cRUD functionality of orders. It shouldn’t have logic for creating an invoice or sending notifications or anything else. For these tasks, having service classes is a better solution. Again, those who have worked with Spring (Java) knows that you can have Service class which then calls Repository class for database related logic. Off-course you can go further to DAO pattern. So from Repository you call the DAO class which then is used for database related logic.
@MrFluteboy1980
@MrFluteboy1980 Жыл бұрын
Great video. I know I'm late to the party, but I think throwing and catching Exception isn't such a great idea. Exception is so broad, you may end up catching a completely unrelated exception. I think it's better to throw and catch a more specific exception, like 'InvalidArgumentException' or 'RuntimeException'.
@misha-pitegorsk
@misha-pitegorsk 2 жыл бұрын
Thank you very much Sir! Finally, here I found the answer to my question, which I asked many people. I've been using repositories so far and didn't know it was bad practice already. But how do you feel about architectural patterns like Porto, where we have actions and repositories and tasks. And, does it make sense at all to split the project into containers, each of which has its own route, controller, model, and so on. Or such a solution is only good for large projects.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Yes, I see things like Porto, Lucid, DDD and others mostly for large projects/teams, for smaller projects it's kind of over-engineering just for the sake of "some" structure.
@woodhouse6018
@woodhouse6018 2 жыл бұрын
Thankx à lot
@jeremyvanderwegen1467
@jeremyvanderwegen1467 Жыл бұрын
What about: If you would have a Customer model, that extends CustomerService, and CustomerService extends Eloquent Model. That way you can call a method on the object, for instance $customer->redoVerificationProcess(). No need to put the Customer model in an argument of a service class and no need for auto resolving a service class inside the controller. Also, Customer model will still be tiny and readable for relationships, mutators, scopes etc.
@Adam-uu8dc
@Adam-uu8dc 2 жыл бұрын
Using invoke in action class is cool, you don't have to remember mething name, action class behave as method itself
@dirkk.6828
@dirkk.6828 2 жыл бұрын
Hello, I am a big fan of your Kannal! I look forward to a new video from you every day. Keep up the good work! I still have a question about Laravel: I have several external $_SESSIONs and would pass those to the in a Laravel session -> Session::put('example', $_SESSION['example']. Unfortunately I get the message that the variable $_SESSION was not defined. Do you have a tip for me?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
I don't remember ever using php session array in Laravel, so no tip from me, sorry
@mohamedlaminefall6729
@mohamedlaminefall6729 2 жыл бұрын
I think service class is better because you can put all the logic of the controller inside the service, that way the controller is getting shorter and more readable
@kirayamato6128
@kirayamato6128 2 жыл бұрын
In java or groovy, Services class is all about businesses layer and logic. Do the internal logic in service and call it in controller. Controller should not use complicated logic and sql queries, let the service handle it.
@tahaabujrad7806
@tahaabujrad7806 2 ай бұрын
Great Video @Laravel Daily. I am using the same structure as you, except that my services contains only static methods instead of regular methods, will having such methods have side effects on the project? Another question, Is there a name for this structure of having classes with static methods ? Thank you in advance
@LaravelDaily
@LaravelDaily 2 ай бұрын
Static methods are totally fine if you choose to use them. I have a few videos about them: www.youtube.com/@LaravelDaily/search?query=static
@muhammadqamarhussain5565
@muhammadqamarhussain5565 2 жыл бұрын
Can we use services and action classes in livewire component?
@coolcha
@coolcha 2 жыл бұрын
Wonderfully helpful video again. Is there an artisan command to create the service?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
You probably haven't watched the full video, I mentioned that there isn't.
@coolcha
@coolcha 2 жыл бұрын
@@LaravelDaily Apologies - I must've missed it. I suppose one could create a custom artisan command for it using your other video kzbin.info/www/bejne/Y6OWiKGPrpyaapo right?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Yes if you wish.
@ronaldbaljeu1612
@ronaldbaljeu1612 2 жыл бұрын
Nice guide. So if you do (heavy) processing but don't need to return anything: use jobs. If you have to return something and you only need 1 method: use actions (but you can use services as well). If you have more than 1 method: use services. One question though. I'm concerned about having a large Services folder with a lot of "miscellaneous" files laying around (not all of them being controller related) and doing impact analysis on these files. When you want to change the behaviour of a service class, how do you track down where it is being used? Do have any thoughts about organizing these files? Should we store controller related service classes in a different location from other service classes?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Without practical example, it's hard to say. But generally, you can structure services into subfolders
@Jurigag
@Jurigag 2 жыл бұрын
Honestly - just use CQS, it's not so hard pattern, put your reads/queries into query classes(most likely interfaces and some implentations), and create commands and handlers for creating invoice, this way you have most clean code you can have.
@just_ai_things
@just_ai_things Жыл бұрын
In my opinion, Model should be thin and contains only database configs, accessor and mutators. All database related (for example CRUD) operations should be in the respected Model Repository. Service class will utilize the model repository and do either database operation or external API call.
@diegomelgar2696
@diegomelgar2696 Жыл бұрын
Thank you very much for what you have said in this video. I am not an expert in DDD but in you personal opinion, I would like to know if there would be some other actions/services that must be disptached o executed from the order invoice, should they be called in the controller one after the other? or can they be called inside the service? which for me makes more sense that a service or services can be called insider other services in order to communicate between each other. Nice video Povilas!
@diegomelgar2696
@diegomelgar2696 Жыл бұрын
One side note for the last thing I said about communication, this makes the controller cleaner as well.
@kenjohnsiosan9707
@kenjohnsiosan9707 2 жыл бұрын
Thank you for another great tutorial Sir..by the way offtopic question, what's the editor extension that you use that prints the parameter name? thanks in advance. e.g \Exception(message: 'Order already....')
@LaravelDaily
@LaravelDaily 2 жыл бұрын
It's phpstorm without any extensions
@kenjohnsiosan9707
@kenjohnsiosan9707 2 жыл бұрын
@@LaravelDaily I see. Thank you Sir.👍
@wtransporter
@wtransporter 2 жыл бұрын
I like all your videos. Thanks for sharing. I don't like controllers with more than 7 base methods, and with long methods. One way to clean controller that I use is FormRequest. Sometimes I transfer responsibility for storing to FormRequest. As a suggestion, I would like to see an example how we can extract bigger filtering (5+ filters has too many if or when statements) of model from controller to Model class or service. Would you recommend something other than scopeFilter for example?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
There are a few packages for filters, search my channel for filters
@kenyawap
@kenyawap 2 жыл бұрын
You could use the built in Pipelines pattern to separate filtering logic into classes that each modify the query then pass command to the next filter class. The pipeline returns a final query which has passed through all the filter classes. To add a filter, simply create a new class and throw it into the pipeline.
@rudolfbruder4674
@rudolfbruder4674 2 жыл бұрын
Thanks for the video. What I find troubling about the model way is that for example if you use elastic search without laravel bridge you end up with array of objects not models and in order to use some methods you have to convert these 'virgin' objects to actual laravel model objects. This idea comes from an eshop solution that we coded where using eloquent models for products took up a lot of memory and was not efficient when using elastic so we ended up with custom Product model not connected to laravel base model class at all. This idea came from one of the most senior php devs in team. What do you think about that?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Well, your example is very untypical but realistic. So yes, if you see that any other framework/pattern/structure works better or more performant than default Laravel, then of course you're free to move away from conventions like Eloquent and replace with your own base classes.
@rudolfbruder4674
@rudolfbruder4674 2 жыл бұрын
@@LaravelDaily Indeed but personally i find it very challenging because they you need developers who understand also vanilla php and logic behind it not just laravel
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Finding developers is always a challenge :) If you take on such non-standard projects, you need non-standard developers :)
@rudolfbruder4674
@rudolfbruder4674 2 жыл бұрын
@@LaravelDaily for a non standard price, that's why i dont think its worth the few mili seconds and ram MB saving. Rather get better VPS. But that's more business and budget domain :) I rembemr how Jonathan Reinink said that people pick technologies such as elastic even though they are not needed. Laravel mysql eloquent can just find you just have to understand queries and rules for memory saving. Also it's not 2000 anymore when the servers were so expensive and limited i guess.
@Giogiova71
@Giogiova71 2 ай бұрын
Service reminded me the architecture of springboot.
@vidhyaprakash85
@vidhyaprakash85 2 жыл бұрын
Sir, In the services class can I define the method as static and call directly using the class name. Is it a good practice? Please let me know.
@vasilyya7578
@vasilyya7578 2 жыл бұрын
It is not good, because it breaks dependency inversion principle.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Here's a video about it: kzbin.info/www/bejne/p2GbiWqXaruZnqc
@wadecodez
@wadecodez Жыл бұрын
I agree with this video however I never use actions. IMO if you want to reuse the same logic in a command, controller, job, etc., then the service should provide commands, controllers, and jobs. It keeps the design close to the framework and it makes your services reusable across projects. With actions, you're instantiating a lot of single use classes which are tightly coupled to your project. For example, if I have an action called ProcessUserPaymentMethod, it seems like a concise action. However, as soon as the requirements change to do something like process a team payment method, or to process additional payment methods like wire transfers, now what? Do I continuing writing new action classes for each case, do I add methods to the action class, or do I rewrite what I have into a service? My rule of thumb is keep models strictly for data relationships, and model configuration like you said. Use controllers to query the db, delegate logic, and render views. Use services to do all the heavy processing and provide extensions to the framework.
@muhammedrafia8881
@muhammedrafia8881 2 жыл бұрын
Povilas, how i insert user id through mass assignment in form request.?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
I can't answer that in a short KZbin comment, without code example
@JamesAutoDude
@JamesAutoDude 7 ай бұрын
If I have multiple roles (admin, company owner, company client); should I have each controller namespace different or should I put it all in one controller and define logic per role?
@LaravelDaily
@LaravelDaily 7 ай бұрын
Personal preference
@rossco5551
@rossco5551 2 жыл бұрын
I've never quite got my head around the "auto resolve" you mention at about the 8min mark. Is it only for controller methods that this works? Otherwise how would it not know that $orderService isn't a parameter to be passed in rather than what I understand to be a new blank instantiation of OrderService?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Read the docs: laravel.com/docs/8.x/container#automatic-injection
@rossco5551
@rossco5551 2 жыл бұрын
@@LaravelDaily Yes thankyou, always my starting point but I find sentences like "including controllers, event listeners, middleware, AND MORE" fairly useless in understanding the scope of their power. Just something I've never quite got anyway.
@kevinpallado9638
@kevinpallado9638 2 жыл бұрын
hi what does it do with this line on the part of the character with ` : Invoice ` // public function execute(Order $order) : Invoice
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Just specifies the type that function returns
@geneartista9714
@geneartista9714 2 жыл бұрын
I would rather use your method of creating a Services directory, it seems more readable and easier to manage than the other two, Do you have a tutorial about PEST?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
kzbin.info/www/bejne/oKmrh5SwaM6Cn7c here's the video
@saravanasai2391
@saravanasai2391 2 жыл бұрын
Sir.... This video is really helpful for me..... I request for a Saturday car video to speak about as a beginner. How much knowledge on Core PHP to Master a Laravel or To develop packages in laravel. Its more useful if you add learning path you have added for laravel and the testes like that.... Sry for my bad English sir........ Even any in this community help to find the path to master core PHP..... Thanks in advance
@LaravelDaily
@LaravelDaily 2 жыл бұрын
To be honest, I would learn the basics of core PHP only (variables, if-statements, loops, OOP - there are thousands of free tutorials online), and then dive into Laravel. I don't think it needs the full video.
@michaelerwin8744
@michaelerwin8744 9 ай бұрын
3:43 I think this is going to be difficult to debug. You won't get the log and full back trace of the error.
@msw0629
@msw0629 2 жыл бұрын
You are a fantastic teacher! Is it too confident to say that just use service? If later on service becoming cumbersome which requires refactor, just separate them using action and job. So service will be only end point that a controller touches?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Can be, yes, it's your personal preference
@jamols09
@jamols09 2 жыл бұрын
Question, this one is quite complex to me to understand how does $order->invoice()->create(); works ? because I'm used to Model::create(['name' => $var->name , etc..]); Im not sure if it does the same thing?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Yes, but in this example, invoice has no fields except invoice number which is set automatically.
@miguelradaza8180
@miguelradaza8180 Жыл бұрын
what tools you use for documentation of apis in laravel, can we use swagger in laravel?
@LaravelDaily
@LaravelDaily Жыл бұрын
I like to use Scribe. And you can use swagger, yes, there's a package for it
@user-lj2ou4db3c
@user-lj2ou4db3c 2 жыл бұрын
What about when we have request(create form is submited) should we pass whole request to services method create and return what ?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
No, ideally you should pass only the data that services actually need to work with.
@user-lj2ou4db3c
@user-lj2ou4db3c 2 жыл бұрын
@@LaravelDaily Thanks for the answer, do you have video or link with example
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Search "service" on my channel, quite a few videos about them, not sure if those are the exact examples. Also, I have this project: laravelexamples.com/tag/services
@kcirerick100
@kcirerick100 2 жыл бұрын
What if for example, on my index controller method I have a large query with 30+ lines for listing some table data. In my case this query is being used only in this controller method, so should I create a separate Action/Service only for this logic?
@QueeeeenZ
@QueeeeenZ 2 жыл бұрын
You could create a "Query" class for that large query. Or you can also put it on your model. And I don't think it's wrong to use a Repository pattern either. Your choice.
@kcirerick100
@kcirerick100 2 жыл бұрын
I've never seen the Query solution, I'll search for that. Thx bro 👍
@LaravelDaily
@LaravelDaily 2 жыл бұрын
It's your choice. If that 30+ lines make it hard for you to read/navigate the Controller, then yes, it should be separated. One of the goals of separating logic from the controller is readability, so any developer in the future could easily browse through controller and read all the methods, then diving into the one they're interested in, by clicking on the exact place with IDE.
@AksoomHussain7866
@AksoomHussain7866 Жыл бұрын
why don't consider observer instead of service for status update or sending notification?
@LaravelDaily
@LaravelDaily Жыл бұрын
Also possible, yes
@bw7868
@bw7868 Жыл бұрын
Laravel directory structure itself is far from optimal if you plan to make a big project. when it's a big project which has a big business logic, I use the module structure like in Python frameworks i.e., Django. This structure for me is the best for big projects, every module has its own views, controllers, models, jobs, events, actions, business logic ..., and you don't have travel back and forth between unlinked directories when you're working on a single module. I think Laravel in the future should consider this structure and must be an option while setup to choose this structure if you prefer.
@ward7576
@ward7576 2 жыл бұрын
Question - if all you do in handling is just responding with certain response, why not just let it bubble up to Handler class and define "render" method there to do the same? IMO, much clearer. Sure, if you want to handle it differently, you can use try/catch.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
It's hard to comment on your theoretical thoughts, without a real full practical example with Handler and render. It depends on the exact situation.
@ward7576
@ward7576 2 жыл бұрын
@@LaravelDaily In my case, I did a lot of API development where Laravel serves backend for React Native / other mobile stack applications. Usually exception would be handled with JSON response with a certain HTTP code. Usually took shape of extending default Exception class by something like ApiException. It would implement render method that would take injected message and code and transform into response. Since this was for most exceptions, it really cleared up controllers. For those cases where we need something different - yes, then I'd go for try/catch and handle things differently.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Yes, now it makes more sense, with that additional context. Agree to move exception logic to the global handler.
@AbdulRehman-mw5sc
@AbdulRehman-mw5sc 2 жыл бұрын
Sir, I am agree with your concept and kinda belive that we should re-factor our code base so that it means something readable to someone else or to our self in future times also but what about the performance, where will it goes with bunch of code and more database fetch calls with eloquent, is more classes will not slow it down???
@LaravelDaily
@LaravelDaily 2 жыл бұрын
No, more classes doesn't slow down the script. Maybe in rare cases if you're not careful and initialize a million classes, maybe that would make some difference. But generally, amount of classes doesn't affect the performance, in my experience.
@AbdulRehman-mw5sc
@AbdulRehman-mw5sc 2 жыл бұрын
@@LaravelDaily Thank you very much sir for clearing my confusion. Love from Pakistan ❤
@CyanidePierce90
@CyanidePierce90 Жыл бұрын
How would this work with a repository implementation and would it be good/bad?
@LaravelDaily
@LaravelDaily Жыл бұрын
I'm quite a big anti-fan of repository pattern, expressed in a few videos, like this one: kzbin.info/www/bejne/nZqtlJecjJeqeZo
@OkanUltimatum
@OkanUltimatum 2 жыл бұрын
All these alternatives imply that in the future their functions will be used elsewhere in the project. But in most cases you don't reuse them anywhere and you end up having these one-off classes / methods which is weird to me. In my opinion these one-off classes or methods should be as close to the "calling-class" as possible, like putting them in traits in the same directory or subdirectory with the caller class and make the caller class use that trait, just like the laravel's base controller uses AuthorizesRequests, DispatchesJobs and ValidatesRequests. But again this is just my optical view and I am definitely confused with all these alternatives.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
No, not necessarily will be used elsewhere, and I don't see anything bad with one-off classes/methods. Traits are mostly for REUSABLE things, that you potentially can use in multiple classes.
@Jurigag
@Jurigag 2 жыл бұрын
That's why the most simplified way to handle this - might be not creating controller, just create callable class and put it like this: $router->post('whatever', Cool::class);
@seyedabdorezalabbafi6225
@seyedabdorezalabbafi6225 8 ай бұрын
i think it should be like this controller -> service -> repository -> model
@shahghasiadil
@shahghasiadil 2 жыл бұрын
I prefer Repository Pattern for putting logic and also coming Abstraction 👍😉
@MrStealthWarrior
@MrStealthWarrior 2 жыл бұрын
What about data fetching logic? Should services implement data access on top of Eloquent? Especially if you need a few conditions. Like fetch users who are admins and were created between dates. Or were suspended/deleted. Bloat service with methods for each case? getAdminsCreatedBetween, getDeletedAdmins, getSuspendedAdmins etc. Instead of query builder
@LaravelDaily
@LaravelDaily 2 жыл бұрын
It depends on the situation. If your service becomes bloat then refactor it, also it looks like Eloquent Scopes in your case.
@MrStealthWarrior
@MrStealthWarrior 2 жыл бұрын
@@LaravelDaily that's my point, Eloquent + models + scopes give you a lot of good code to use. And if you remove it from controllers - should you implement almost the same thing inside services, if you need data access and some other logic for a resource? Or use both, service for logic and eloquent for a data access in controllers?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
It depends on the situation. My personal experience is that if Controller method has 1-3 actions to make, it's ok to be in Controller, but if it's more complicated - it should be moved "somewhere", and that somewhere depends on what code is moved.
Junior Code Review: Cleaning Up Laravel CRUD
14:54
Laravel Daily
Рет қаралды 68 М.
Refactor "Senior" PHP Code with Early Returns
12:09
Laravel Daily
Рет қаралды 25 М.
NERF WAR HEAVY: Drone Battle!
00:30
MacDannyGun
Рет қаралды 30 МЛН
Универ. 13 лет спустя - ВСЕ СЕРИИ ПОДРЯД
9:07:11
Комедии 2023
Рет қаралды 6 МЛН
1 or 2?🐄
00:12
Kan Andrey
Рет қаралды 29 МЛН
Laravel + Service Pattern + DTOs = ❤️❤️❤️
17:52
Przemysław Przyłucki
Рет қаралды 43 М.
Laravel's secret weapon: macros (watch me code)
23:46
Aaron Francis
Рет қаралды 19 М.
Why is Laravel NOT used in Big Development Projects?
11:53
Stefan Mischook
Рет қаралды 170 М.
Laravel Junior Code Review: Security and Consistency
17:29
Laravel Daily
Рет қаралды 48 М.
Laravel Code Review: Why NOT Use Repository Pattern?
14:21
Laravel Daily
Рет қаралды 76 М.
When should you pick Laravel over WordPress?
26:54
viewSource
Рет қаралды 5 М.
Laravel Eloquent: Deeper Relationships with One Query
10:37
Laravel Daily
Рет қаралды 137 М.
Eloquent Performance: TOP 3 Mistakes Developers Make
7:59
Laravel Daily
Рет қаралды 47 М.
Two Things Laravel Services Should NOT Do
8:20
Laravel Daily
Рет қаралды 21 М.
VOCÊ ME AJUDARIA ?
0:46
JHONIC
Рет қаралды 23 МЛН
Surprised 😳🤩🤩❤️🔥🥳
0:35
Okanutie
Рет қаралды 8 МЛН
There’s a surprise balm in every snack!? #challenge #candy
0:10
We Wear Cute
Рет қаралды 42 МЛН
Qual ELEMENTO é Melhor para ESCAPAR😱 #shorts
0:26
Lucan Pevidor
Рет қаралды 11 МЛН