Тёмный
No video :(

Laravel API Resources for Same Model: Re-Use or Create New? 

Laravel Daily
Подписаться 143 тыс.
Просмотров 23 тыс.
50% 1

If you want to use Eloquent API Resources for multiple Laravel API endpoints, should you use the same resource, or create a different one? Let's discuss.
My courses related to APIs:
- React.js + Laravel: SPA CRUD with Auth laraveldaily.t...
- Vue.js 3 + Laravel 9 SPA: CRUD with Auth laraveldaily.t...
- Flutter Mobile App with Laravel API laraveldaily.t...
- How to Create Laravel API laraveldaily.t...
- - - - -
Support the channel by checking out my products:
- My Laravel courses membership: laraveldaily.t...
- Laravel QuickAdminPanel: bit.ly/quickad...
- Livewire Kit Components: livewirekit.com
- - - - -
Other places to follow:
- My weekly Laravel newsletter: bit.ly/laravel-...
- My personal Twitter: / povilaskorop

Опубликовано:

 

22 авг 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 59   
@IlPandax
@IlPandax 2 года назад
I think that resources are like form requests. At the beginning you try to use one single item for everything, then you understand that creating a new file costs you nothing.
@chibuikeumezinwa7827
@chibuikeumezinwa7827 2 года назад
With conditional resource like when($request->routeIs(`list`)) you may somehow manage to use same resource class for all endpoints
@cristianganzer2057
@cristianganzer2057 8 дней назад
I really liked this approach of separete things to avoid future issues and I think the use of methods as whenLoaded of the own resource collection can be useful too, for resources with more data!
@OtiszWasTaken
@OtiszWasTaken 2 года назад
I'd never recommend to use `MyResource::collection()` method, because it returns the immutable AnonymusResourceCollection class. A resource class should have only one purpose: representing a single model (e.g. a post in the show, store and update methods). If you want to create a list of them, then create a separate resource collection class which collects the resource class (or a separate resource class for list elements if needed). Separating resources and resource collections for different purposes are cost almost nothing but gives you more control.
@user-wn9cv7el2i
@user-wn9cv7el2i 2 года назад
Hello sir, excuse me, can you have some link to the example ? Thanks for the tip
@OnlinePseudonym
@OnlinePseudonym 2 года назад
I'd recommend not naming a resource a plural (categories) but sticking the convention of using a singular (category). The resource that is serialised in the toArray method is always a singular item. Also, it's surprising to have some resources in singular and others in plural. I suggest resource names of: CategorySummaryResource and CategoryDetailResource. But to each their own.
@chlouis-girardot
@chlouis-girardot 2 года назад
Again, thanks to share this specific topic ! It gave me such a headache when i tryed to merge the small one into the biggest. I never successed of course. I hate to repeat my self but here ... i guess we have to !
@azelen
@azelen 2 года назад
I think it always depends on a specific scenario, sometimes it makes sense to reuse the resource (if for example I have a resource with 10+ fields and need to optionally include/exclude one or two of them, this way it is easier to maintain the resource later in case if the model changes) and in other situations it makes sense to create separate resources when the difference is significant. I've used both approaches.
@leonardoldr
@leonardoldr 2 года назад
I usually preffer to leave the Controller/Query with the responsability to get only the data I want to display, and the Resource as much dummy as I can, using $this->when() to display stuff and not placing too much logic on them, at max giving some styling to the output, in that way I minimize the number of resources that grow like weed on big projects and have a more flexible way to use them. But of course, it's not a golden rule, when you realize that you need different keys or value formatting, it's a call for a new resource.
@SunilYadav-tm6kt
@SunilYadav-tm6kt 2 года назад
Hello Povilas Korop, Instead of creating different resources for the different endpoints for same modal, I prefer to use a switch case based on route name in the same resources for all endpoints. Maybe it is better if we compare it with different resources for the same modal.
@LaravelDaily
@LaravelDaily 2 года назад
That's another way of doing it, yes.
@andywong2244
@andywong2244 Год назад
this is interesting. will try this one out. thanks for the idea!
@5dmat-web
@5dmat-web Год назад
I have had this issue before, my personal solution was to make a base class that holds the share attributes like id, name, and created_at so that I am sure it will not be touched, that was very important in my scenario because in some cases I need to send some attr in all APIs that have this resource, other attributes that exist in some APIs and not in another I make an isolated class for each API I need, with this solution I mixed-use part of code and isolated business logic, and the important thing i have very clean resources without any conditions
@TheBaraa2011
@TheBaraa2011 2 года назад
I think we can use one resource with "select" a params on the query and use in resource when function .. return [ 'id' => $this->when($this->id, function () { return $this->id; }), ]
@MrNotsoft
@MrNotsoft 2 года назад
Yes, I recently came to the same conclusion. On one's own)
@bboydarknesz
@bboydarknesz 2 года назад
Yes I agree with this. Every request usually have different data needed. But I just wondering, what should we do to keep the keys same and consistent? Maybe in a team, A use 'desc' key but B use 'description' key. Not sure if I need make constant variable in Traits for each keys? Or maybe a new class?
@LaravelDaily
@LaravelDaily 2 года назад
Good catch, with different classes it's hard to keep consistency, I guess it's just a matter of communication in a team.
@intipontt7490
@intipontt7490 2 года назад
Personally, I prefer inlining instead of using Resources. That way, I can see in the controller what is returned. Using Resources has always seemed like chasing the "slim controller" idea by sweeping the code under a rug (Resources, Actions, Services) without really simplifying anything. There are some nice things you can do with Resources however, like conditionally returning columns using then when() method or rendering related models as their own resources. In the absence of that kind of logic, I don't think Resources are needed.
@rahulkumarsingh1716
@rahulkumarsingh1716 2 года назад
u can override the constructor to use same resources class for different purpose
@alila3883
@alila3883 2 года назад
I think one resourse best way but inside resourse class use match or switch method to use the correct route…
@nabeelyousafpasha
@nabeelyousafpasha 2 года назад
It somehow convinced me to adopt this new idea
@mohamadcheaib
@mohamadcheaib 2 года назад
What about relations between api resources, so if i want to use comments resource inside post resource and so on, it can be endless to create resource for each request! I think it is better to work arround with some conditions even to let the full description if will not cost alot for memory usage as we always use pagination for such senarios or getting some fixed number of records. So creating a new resource for each route will cost us more, as we are not reusing the code, any change in one table should be reflected in all resources.
@LaravelDaily
@LaravelDaily 2 года назад
Well, I don't think you would have THAT many resources so you wouldn't remember them, especially if they are in the same folder. But I see your point, if you have a chance of a lot of future changes, then perhaps a reusable structure with some conditions is better, for your case.
@jacquesmatike9289
@jacquesmatike9289 2 года назад
Also maybe use the helper request inside categories resources and make some conditions? And then reuse original CategoryResource ?
@0xshaheen
@0xshaheen 2 года назад
Yes I agree with you
@LaravelDaily
@LaravelDaily 2 года назад
That's another way of doing it. But somehow it feels to me like a "code smell" that response has access to the request. Controller should cover the parameters processing.
@kaustubhbagwe6718
@kaustubhbagwe6718 2 года назад
We have access to $request in CategoryResource file, so cant we merge additional input using $request->merge(['descriptionRequired' => true]); // before returning CategoryResource and then $this->mergeWhen($request->descriptionRequired, [ 'description' => $this->description ]); // in CateogoryResource file to merge description field when ever required
@ljubicasamardzic7819
@ljubicasamardzic7819 2 года назад
I literally had the same issue a week ago and also opted for separate resources.
2 года назад
How do you solve situation, when you change your model and you need to update all Resources?
@LaravelDaily
@LaravelDaily 2 года назад
I update all resources, then. It's a rare occasion and I don't remember creating more than 3 resources per model.
@anthony.guimack
@anthony.guimack 2 года назад
Good evening, a question: How can I send data from a form (customer_name, country, state, city, telephone and others) to a microservice and that it can insert the data or query it, taking into account that I have sent several parameters. Regards :)
@kirayamato6128
@kirayamato6128 2 года назад
I don't use api resources because it will have am extrea query when performing the controller actions.
@PeeNoiseKulangot
@PeeNoiseKulangot Год назад
How about Complex nested Resources with relationships?
@user-cf5uf7vf2g
@user-cf5uf7vf2g 2 года назад
agreed with more readability, don't wrap too much layer.
@NathanBudd
@NathanBudd 2 года назад
Is your React course just normal React, or NextJS? I'm looking for SSR but with a Laravel API and Auth. I was going to start with the Laravel Breeze and the NextJS template that is recommended in the docs.
@LaravelDaily
@LaravelDaily 2 года назад
Normal react, without SSR. That's a course for React beginners, SSR or frameworks are another new level.
@MartinBojmaliev
@MartinBojmaliev 2 года назад
When Im building API, I never use Resources. I just return models as they are. (of course hiding sensitive data). Is this bad practise?
@LaravelDaily
@LaravelDaily 2 года назад
No, whatever works for you, if you don't need any transformations from the model
@aribiali3574
@aribiali3574 2 года назад
Thank you a lot 💙
@ezz_dev
@ezz_dev Месяц назад
the course link says "This product is not avalable"
@LaravelDaily
@LaravelDaily Месяц назад
I've moved my courses in 2022 to my own platform, see laraveldaily.com/courses
@thewizardguy1337
@thewizardguy1337 2 года назад
how do you handle documentation for this? i find it very tedious to manage 4-5 different resources for the same model in the docs
@LaravelDaily
@LaravelDaily 2 года назад
Why/how do you document the resources? You should document API endpoints, not resources, at least that's what I tend to do.
@thewizardguy1337
@thewizardguy1337 2 года назад
@@LaravelDaily for reusability -- i make schema in openapi and (try) to reuse them as much as possible -- descriptions of the exact same named property are a nightmare to update in more than one place
@LaravelDaily
@LaravelDaily 2 года назад
Hmm, I haven't worked with openapi for a long time so it may make sense in your case. I document just the endpoints for the API with Scribe, it doesn't care about API resources inside.
@jufrensiusbarasa6539
@jufrensiusbarasa6539 2 года назад
Can you make a tutorial video for users, roles and permissions using spatie? I'm having a problem with update role and it throws an error 'this name is already taken'. Thank you in advance
@LaravelDaily
@LaravelDaily 2 года назад
I don't think you need a tutorial video, there are a lot of them on the internet. You need to solve specifically your problem, so you need someone's help to debug it. Unfortunately, I don't have enough free time, to do that. Put your problem on Laracasts forum, for example.
@jufrensiusbarasa6539
@jufrensiusbarasa6539 2 года назад
@@LaravelDaily Thank you for your suggestions
@nabeelyousafpasha
@nabeelyousafpasha 2 года назад
So it seems that NAME coulmn of roles table is unique and could you share your code of updating role, I would be glad to help you. Thanks
@nurmuhammetallanov9180
@nurmuhammetallanov9180 2 года назад
👍👍👍
@zhgaaaaaan
@zhgaaaaaan 2 года назад
categoriesResources::make() Vs new categoriesResources() ?
@LaravelDaily
@LaravelDaily 2 года назад
Personal preference
@bmtamim7818
@bmtamim7818 2 года назад
Hello sir, Why my eager loading is not working? It create multiple queries. Relation: prnt.sc/JUdR11Wh1oMd Query : prnt.sc/77LNQUCsNQvb Result : prnt.sc/t0HoBVm3fOrU Also, How can I avoid spatie permission queries on every page. I have to check the permission. Visual Details : prnt.sc/8riyzAY7ujO5
@LaravelDaily
@LaravelDaily 2 года назад
I think it's an expected behavior that every page checks the permission, that's what it's supposed to do, no? With eager loading, have you tried leaving just with('orders.items') alone? And actually, I think it DOES the eager loading, one query per relationship.
@bmtamim7818
@bmtamim7818 2 года назад
@@LaravelDaily yes, Its run one query per relationship. Is it possible to run only one query?
@user-fi1uh8ct2j
@user-fi1uh8ct2j 2 года назад
@@bmtamim7818 you cant with built-in Eloquent ORM behavior.
@bmtamim7818
@bmtamim7818 2 года назад
@@user-fi1uh8ct2j Got it..thanks
@bmtamim7818
@bmtamim7818 2 года назад
@@LaravelDaily Thanks a lot..sir❤️
Далее
Laravel: Create Public API with Cache and Rate Limits
12:18
I forced EVERYONE to use Linux
22:59
Просмотров 415 тыс.
PEDRO PEDRO INSIDEOUT
00:10
Просмотров 2,7 млн
Laravel Security: Top 7 Mistakes Developers Make
11:16
Brutally honest advice for new .NET Web Developers
7:19
Don't Use Polly in .NET Directly. Use this instead!
14:58
Good APIs Vs Bad APIs: 7 Tips for API Design
5:48
Просмотров 229 тыс.
Laravel + Livewire todo app (and so much more)
16:41
Просмотров 39 тыс.
Eloquent Performance: TOP 3 Mistakes Developers Make
7:59