Laravel + Service Pattern + DTOs = ❤️❤️❤️

  Рет қаралды 43,271

Przemysław Przyłucki

Przemysław Przyłucki

Жыл бұрын

Hi guys!
In this video series, I'll be showcasing a simple way to integrate service pattern into existing Laravel applications. We'll start with a super simple example - an app that stores blog posts from the app and the api.
We'll do a couple of iterations before landing in type-safe service pattern solution that utilizes DTOs.
For more content visit saaslaravel.com

Пікірлер: 98
@free2idol1
@free2idol1 9 ай бұрын
11:15 using `tap()` to get the updated model instance after the update. This is a great thing for me. Thanks for fabulous video.
@abdullah.alhabal
@abdullah.alhabal Ай бұрын
yeah
@peterpardo4138
@peterpardo4138 9 ай бұрын
This is a GEM! Thank you so much for sharing this. I really appreciate you!
@kpomeru
@kpomeru 11 ай бұрын
I had to take my time to understand this from the solution back to how it was implemented. This is insightful
@sunnysk43
@sunnysk43 Жыл бұрын
Very very useful! Will definitely use it in my next project! Looks very promising.
@e-raticartist
@e-raticartist 2 ай бұрын
huge improvement in the quality of my code after this, next level content
@XTishka1980
@XTishka1980 2 ай бұрын
Amazing! Thank you for your lessons
@dongham2865
@dongham2865 Жыл бұрын
I like this video. This is exactly the pattern I want. Thanks!
@GayanSanjeewaKarunarathne
@GayanSanjeewaKarunarathne 7 ай бұрын
This is just awesome. Good job mate! To be honest I think you covered more than just Services and DTOs. Keep it up 👍
@unknownstalker2624
@unknownstalker2624 2 ай бұрын
Man, you are just awesome! Your content really helped me!
@casweeney
@casweeney Жыл бұрын
This video was really helpful, a lot of things now make sense. Thanks so much.
@christiansosa5484
@christiansosa5484 Жыл бұрын
Great stuff man! thanks for sharing
@soyarenamovediza6498
@soyarenamovediza6498 4 ай бұрын
Loved this video, thanks! You explained many patterns and did very well. I would like a video from yourself explaining some real life scenarios where these patterns really shine by themselves. I’ll share this video.
@zachariascreutznacher3093
@zachariascreutznacher3093 Жыл бұрын
Very nice, simple and clean description about Services and DTOs in Laravel, thanks man 👍
@natenatters
@natenatters Жыл бұрын
Great video! Thats very similar to how we are structuring our application. I like your approach of showing the iterations, a good way to learn. Thanks.
@saaslaravel
@saaslaravel Жыл бұрын
Thanks Natan! If you sprinkle some DDD on top it gets even better 🤓
@GonzaloGuevaraFreire
@GonzaloGuevaraFreire Жыл бұрын
Muy buen video. Muy entendible y progresivo.
@mayanksgajjar
@mayanksgajjar Жыл бұрын
You just earned one more subscriber, thanks for sharing valuable information...😊
@SerG63rus
@SerG63rus Жыл бұрын
One of the best videos which let’s you understand clever way to write code in just less than 20min. Very very useful and pure. Thank you!
@VimKanzo
@VimKanzo 8 ай бұрын
I couldn't agree any better
@AhmadAli-jb6ri
@AhmadAli-jb6ri 4 ай бұрын
❤❤ Thanks for this tutorial...
@mohammadravand4351
@mohammadravand4351 6 ай бұрын
thank you very mutch, this is very excelent video a bout laravel service pattern, 😍😍😍🥰
@chlouis-girardot
@chlouis-girardot Жыл бұрын
Nice work ! Thanks for sharing 🙏
@saaslaravel
@saaslaravel Жыл бұрын
Thanks for watching!
@lucasdepace
@lucasdepace Жыл бұрын
Very cool! Thanks for the video Keep making more videos please!
@saaslaravel
@saaslaravel Жыл бұрын
Thanks Lucas!
@AdrianoAlves7
@AdrianoAlves7 Жыл бұрын
I really do not understand why add complexity and more entities when we have some methods in Laravel to get all the validated data from a request. I like and i employ the Service Pattern because we can separate the app business logic from models and controllers, but the DTO.. oh my... i can't see any need for this. I would like to see a Video from you about Model Events and BroadCasting them. Thank you and congratulations for your great work, Przemyslaw. Greetings from Brazil.
@saaslaravel
@saaslaravel Жыл бұрын
Hi Adriano! Thanks for the kind words. Lemme explain the reasoning: The biggest reason why DTOs are useful is it unifies the data passage through your application. Let's say you have a piece of business logic that needs to be executed from your app, public api, command and a job. DTOs ensure that proper data gets passed to the service. Also, if you ever add a property, it will cause errors in places where it was not implemented / handled which also prevents bugs
@felipeflashmaster
@felipeflashmaster 8 ай бұрын
So using the Model itself as a DTO would be the same, right? or how in typescript to use an interface
@irlnidallah
@irlnidallah 25 күн бұрын
@@felipeflashmaster using the Model as a DTO itself would clutter the Model into a mess, if you're planning to implement DRY, that would not be a recommended approach.
@B0re_d
@B0re_d 10 күн бұрын
I would add the transformation method to request classes. In my opinion you should not have to extend DTO classes when adding new pieces of code eg. API v2 instead you should have a method called asDto(or toDto) in the request class and call them instead of making X static factory methods. Overall great content :)
@abdurashid_dev
@abdurashid_dev 11 ай бұрын
Helpful content! Thank u!
@saaslaravel
@saaslaravel 11 ай бұрын
You're welcome!
@MrSfinks13
@MrSfinks13 8 ай бұрын
Cool! Thank you!
@SeyedaMansour
@SeyedaMansour 8 ай бұрын
wow, this was great
@brunofunnie
@brunofunnie Жыл бұрын
B-e-a-u-tiful!
@gazorbpazorbian
@gazorbpazorbian Жыл бұрын
awesome video dude! saw it again :D
@saaslaravel
@saaslaravel Жыл бұрын
Legend!
@laxman123in
@laxman123in 9 ай бұрын
Awesome
@codewithtee
@codewithtee Жыл бұрын
This is good. Simple and easy to understand... I have always wanted somethinh simple for dto instead of a package... Will be improving some project with this implementation
@saaslaravel
@saaslaravel Жыл бұрын
Thanks! Glad you enjoyed it and good luck on your project
@codewithtee
@codewithtee Жыл бұрын
While refatoring, I wonder how you would handle Request for update that has fields set as sometimes for validation. Considering for patch request, not all fields will be supplied.
@saaslaravel
@saaslaravel Жыл бұрын
@@codewithtee Often times I just duplicate the request, I like this approach because it's the most flexible one. You could try and extract common rules but as the resource gets more complex I think it just adds unnecessary complexity in something that should be sime. Another solution is to simply check the method in the request and modify the rules array but I find it harder to read :)
@toheebabiodun70
@toheebabiodun70 Жыл бұрын
same here too..
@borakayalar
@borakayalar 5 ай бұрын
Perfect
@user-dk4or7bs2q
@user-dk4or7bs2q Жыл бұрын
So nice
@midclock
@midclock Ай бұрын
Nice tutorial! You can check ide-helper to generate model auto completion for properties. For dtos I find laravel-data by spatie a very good solution. Cheers
@saaslaravel
@saaslaravel Ай бұрын
Yeah I use both of them in my workflow! Def worth checking out for anybody interested though!
@bakre_dev8728
@bakre_dev8728 Жыл бұрын
Cool
@NoNameUkr
@NoNameUkr 6 ай бұрын
I prefer to pass array into static DTO method, then Request, for me its much safety, u can use this DTO from wherever u want, not only from Controller. Example: tomorow u will need to create Post from console command or from Job
@saaslaravel
@saaslaravel 6 ай бұрын
Which you can still do by instantiating the DTO from the constructor. Imo array passing loses all of the benefits of type checking built into the class
@antonsobchuk7690
@antonsobchuk7690 9 ай бұрын
Great job, man. What’s the theme of phpstorm you are using btw?
@nikolayrogoza4240
@nikolayrogoza4240 16 күн бұрын
Great tips, but i more like to use different actions as class, not as a part of service. Its easy to extend from basic model to others
@gazorbpazorbian
@gazorbpazorbian Жыл бұрын
this is a very cool video.. nicely explained. what about making a video about php types?
@saaslaravel
@saaslaravel Жыл бұрын
Thanks so much! Types as in strings, ints etc? What would you like to know about them?
@gazorbpazorbian
@gazorbpazorbian Жыл бұрын
@@saaslaravel everything hehe, like using a separated file, best practices, how to use it in a function like boot(): void and all that stuff.
@VipStudio
@VipStudio 3 ай бұрын
When you have form request class included into ur method you dont need to do $request->validated cuz the data is already validated otherwise it throws validate exception until first line of code starts compile from function
@VipStudio
@VipStudio 3 ай бұрын
And you dont need to use Dto u can just do create($request) //already validated clean data
@chris11651
@chris11651 Жыл бұрын
very informative, thank you very much! what theme do you use in your IDE?
@saaslaravel
@saaslaravel Жыл бұрын
Thank you! It's called Catpuccino Mocha
@chenten420
@chenten420 Жыл бұрын
This is a really great video! Is there a repository where I can check the code for this example? I would greatly appreciate it.
@saaslaravel
@saaslaravel Жыл бұрын
I don't have it unfortunately but will probably start doing it going forward
@LowVi
@LowVi Ай бұрын
Really good man! I would like to know what you think about adding an extra layer: the repository. Because thats kinda whats going on my in job rn, laravel + service pattern + dto + repository, I feel like the Model itself could act as the Repository, what do you think?
@saaslaravel
@saaslaravel Ай бұрын
It really depends on what you are looking for from the solution. I'd say - if you don't have a good reason to introduce a repository - don't do it. If you want to have more fine grained control over your persistence layer (i.e to handle CQRS more easily) go for repository!
@artemkanarskyi8231
@artemkanarskyi8231 Жыл бұрын
Thanks is very helpful! I want ask as how use DTO when you have relations for example Post has many Comments. In PostDTO comments will be array/collections of CommentsDTO or simple array of ids?
@saaslaravel
@saaslaravel Жыл бұрын
Thanks Artem! It really depends on the scenario, I think there is a use-case for both Option A: Nested models created all at once. Example: You create BlogPost and it has different "sections" of content, or you create a Recipe that has Ingredients Solution: In this example you'd have a RecipeDTO that has all of the recipe properties, and either an array of IngrednetDTO, or a IngredientDtoCollection (the latter if you want something that's more type-safe) Option B: Creating a new model and associating it with existing ones Example: You select which users should have access to a project Solution: In this example you'd have a ProjectDTO, that'd contain an array with IDs of users to associate and then simply attach it to a pivot table Lemme know if this makes sense!
@artemkanarskyi8231
@artemkanarskyi8231 Жыл бұрын
@@saaslaravel Thank you for your help.
@JSONFX
@JSONFX 3 ай бұрын
What font are you using on this video? Thanks!
@lassestube
@lassestube Жыл бұрын
You don’t need constructor, you can bind service in controller method automatically...
@saaslaravel
@saaslaravel Жыл бұрын
That's true, but I prefer using constructor. The method tends to have 2/3/4 arguments - with type hints it takes a lot of space, and when it lives on constructor level I can just define it once :D
@lassestube
@lassestube Жыл бұрын
@@saaslaravel makes sense as well :) I tend to use actions in method binding and if I use a service in more than one method I would promote it to the constructor.
@zulfikarditya7142
@zulfikarditya7142 Жыл бұрын
Very nice tutorial. But i have a question, how to use DTO in many relational data like transaction with many items or something?. and we'll be use service as well,
@saaslaravel
@saaslaravel Жыл бұрын
It really depends on the usecase so it's hard to give you a good response here but you can also nest them and utilize arrays with phpdoc type hinting to skip some of the type limitations of php
@nicolascanala9940
@nicolascanala9940 Ай бұрын
Hey! How do you approach having different validation rules in the store and update actions? For example, a StoreBlogRequest which marks all fields as required, VS an UpdateBlogRequest which doesn't (for example, you just wanna update the name). Would you create more than one DTO and mark the properties as nullable?
@saaslaravel
@saaslaravel Ай бұрын
Hey there! It depends on the situation, generally speaking with updates I'd not go with nulls because partial updates are pretty sexy - if you use spatie/laravel-data - they handle it out of the box with Optional type hint
@huntwithmeid
@huntwithmeid Жыл бұрын
Well done bro! Great videos. But I have a question here, so what is the benefit of using DTOs? I'm interested to use this in my project, is it hard to implemented in existing project. I'm also using service class.
@saaslaravel
@saaslaravel Жыл бұрын
The main benefit is making sure that the data you're passing is valid data that service can consume. This is especially useful when you have multiple pieces of app - console, public api and internal api calling the same service. You can just start implementing it on new services and then gradually go over existing code! Hope that helps :)
@pwcodigo
@pwcodigo Жыл бұрын
@@saaslaravel Obrigado !
@GonzaloGuevaraFreire
@GonzaloGuevaraFreire Жыл бұрын
Además que simplifica el constructor
@Pavelbrov
@Pavelbrov Ай бұрын
5:50 - what about duplication in BlogPostRequest validation for api and app? Can we get rid of it?
@Pavelbrov
@Pavelbrov 8 ай бұрын
Is "laravel-data" package from spatie doing something similar?
@saaslaravel
@saaslaravel 8 ай бұрын
Yes, it's just a concept that you need to know from scratch. Just a regular, plan, old PHP class. Nothing wrong with using the package!
@iqbalrafli2191
@iqbalrafli2191 8 ай бұрын
Good video, but i have a questions. What if we want to store data to two or more table from one endpoint controller?
@saaslaravel
@saaslaravel 8 ай бұрын
You can include all data into one dto or pass two separate DTOs. It will depend on the usecase
@mihaes7172
@mihaes7172 5 ай бұрын
I don't understand why instantiating a readonly DTO just to pass request vars to a writing service method? what's the 'secret' between request vars and service update method that dto needs to exists inside same controller method, concerning the same Post model? what if there are 25->50 controllers & models in the application? that would generate a lot of fancy classes, code to be reviewed, etc. Sometimes we go overboard for the sake of buzzwords....
@Pavelbrov
@Pavelbrov Ай бұрын
17:20 - Shouldn't our DTO have a method like toArray so that we can manually avoid passing all the parameters? I mean, they correspond to the properties of the model. Or is this a bad practice? Like this public function toArray(): array { $properties = get_object_vars($this); $array = []; foreach ($properties as $key => $value) { $snakeCaseKey = Str::snake($key); $array[$snakeCaseKey] = $value; } return $array; } and then BlogPost::create($dto->toArray());
@saaslaravel
@saaslaravel Ай бұрын
I prefer to be explicit when possible, realistically, just use spatie/laravel-data which handles this out of the box
@3dxspx703
@3dxspx703 Ай бұрын
Yikes. Model mutators and observers will be enough guys. But if you want to Over-engineer your code, then go on with dto or something like repository pattern. 😅
@saaslaravel
@saaslaravel Ай бұрын
Until your app had 1200 endpoints and some places haven't been touched for years - yeah
@3dxspx703
@3dxspx703 Ай бұрын
@@saaslaravel yeah? But I prefer laravel's defaults for easier maintenance and debugging. Also KISS. Pfft
@LucasOliveira-ny6kw
@LucasOliveira-ny6kw Ай бұрын
.
@deecee2204
@deecee2204 6 ай бұрын
Why is this so painful to watch? no offense
@saaslaravel
@saaslaravel 6 ай бұрын
Idk, why is it bud?
@zayedadel8552
@zayedadel8552 Ай бұрын
million times better and understandable than any indian out there that i cannot understand
@MrSfinks13
@MrSfinks13 4 ай бұрын
Thank you! Very useful video, realy!
Laravel: Repository Pattern in practice
27:13
Przemysław Przyłucki
Рет қаралды 10 М.
WOW! Laravel's pipeline pattern is AWESOME
20:39
Przemysław Przyłucki
Рет қаралды 12 М.
1❤️
00:17
Nonomen ノノメン
Рет қаралды 10 МЛН
I CAN’T BELIEVE I LOST 😱
00:46
Topper Guild
Рет қаралды 85 МЛН
Did you believe it was real? #tiktok
00:25
Анастасия Тарасова
Рет қаралды 24 МЛН
Laravel. Сервисы, контракты и внедрение зависимостей
29:18
Lectoria. Обучение веб-разработке.
Рет қаралды 21 М.
Refactoring to action pipelines in Laravel
1:25:03
Michael Dyrynda
Рет қаралды 9 М.
5 Design Patterns That Are ACTUALLY Used By Developers
9:27
Alex Hyett
Рет қаралды 200 М.
Laravel Code Review: Why NOT Use Repository Pattern?
14:21
Laravel Daily
Рет қаралды 76 М.
LARAVEL + Clean Architecture // Роман Постников
24:03
Студия Флаг
Рет қаралды 9 М.
Data Transfer Objects - What Are DTOs - Full PHP 8 Tutorial
13:03
Program With Gio
Рет қаралды 40 М.
Enums considered harmful
9:23
Matt Pocock
Рет қаралды 196 М.
This is the Only Right Way to Write React clean-code - SOLID
18:23
Dependency Injection, The Best Pattern
13:16
CodeAesthetic
Рет қаралды 757 М.
Hisense Official Flagship Store Hisense is the champion What is going on?
0:11
Special Effects Funny 44
Рет қаралды 2,5 МЛН
Как слушать музыку с помощью чека?
0:36
GamePad İle Bisiklet Yönetmek #shorts
0:26
Osman Kabadayı
Рет қаралды 337 М.
Main filter..
0:15
CikoYt
Рет қаралды 14 МЛН