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

  Рет қаралды 23,059

Laravel Daily

Laravel Daily

2 жыл бұрын

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.teachable.com/p/...
- Vue.js 3 + Laravel 9 SPA: CRUD with Auth laraveldaily.teachable.com/p/...
- Flutter Mobile App with Laravel API laraveldaily.teachable.com/p/...
- How to Create Laravel API laraveldaily.teachable.com/p/...
- - - - -
Support the channel by checking out my products:
- My Laravel courses membership: laraveldaily.teachable.com/p/...
- Laravel QuickAdminPanel: bit.ly/quickadminpanel
- Livewire Kit Components: livewirekit.com
- - - - -
Other places to follow:
- My weekly Laravel newsletter: bit.ly/laravel-newsletter
- My personal Twitter: / povilaskorop

Пікірлер: 58
@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
@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 !
@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
@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!
@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.
@nabeelyousafpasha
@nabeelyousafpasha 2 жыл бұрын
It somehow convinced me to adopt this new 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
@aribiali3574
@aribiali3574 2 жыл бұрын
Thank you a lot 💙
@rahulkumarsingh1716
@rahulkumarsingh1716 2 жыл бұрын
u can override the constructor to use same resources class for different purpose
@MrNotsoft
@MrNotsoft 2 жыл бұрын
Yes, I recently came to the same conclusion. On one's own)
@nurmuhammetallanov9180
@nurmuhammetallanov9180 2 жыл бұрын
👍👍👍
@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; }), ]
@ljubicasamardzic7819
@ljubicasamardzic7819 2 жыл бұрын
I literally had the same issue a week ago and also opted for separate resources.
@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.
@alila3883
@alila3883 2 жыл бұрын
I think one resourse best way but inside resourse class use match or switch method to use the correct route…
@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
@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 :)
@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.
@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.
@PeeNoiseKulangot
@PeeNoiseKulangot Жыл бұрын
How about Complex nested Resources with relationships?
@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.
@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.
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.
@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
@kirayamato6128
@kirayamato6128 2 жыл бұрын
I don't use api resources because it will have am extrea query when performing the controller actions.
@ezz_dev
@ezz_dev 23 күн бұрын
the course link says "This product is not avalable"
@LaravelDaily
@LaravelDaily 23 күн бұрын
I've moved my courses in 2022 to my own platform, see laraveldaily.com/courses
@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
@user-cf5uf7vf2g
@user-cf5uf7vf2g 2 жыл бұрын
agreed with more readability, don't wrap too much layer.
@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
Laravel Daily
Рет қаралды 45 М.
Exceptions in Laravel: Why/How to Use and Create Your Own
12:18
Laravel Daily
Рет қаралды 87 М.
Best KFC Homemade For My Son #cooking #shorts
00:58
BANKII
Рет қаралды 68 МЛН
Llegó al techo 😱
00:37
Juan De Dios Pantoja
Рет қаралды 58 МЛН
No empty
00:35
Mamasoboliha
Рет қаралды 9 МЛН
Heartwarming Unity at School Event #shorts
00:19
Fabiosa Stories
Рет қаралды 24 МЛН
#40 Api Resources | Laravel 9 Essentials | Laravel 9 Tutorial
14:56
Laravel Controller: Move Logic to Action or Service Class
10:06
Laravel Daily
Рет қаралды 36 М.
Laravel Eloquent: Deeper Relationships with One Query
10:37
Laravel Daily
Рет қаралды 138 М.
Laravel Junior Code Review: 12 Tips on Everything
15:30
Laravel Daily
Рет қаралды 74 М.
Laravel and External APIs: Get Data with HTTP Client
6:36
Laravel Daily
Рет қаралды 52 М.
Laravel Pivot Tables: Simple to Advanced Many-to-Many
12:24
Laravel Daily
Рет қаралды 119 М.
МТЗ-80, подписывайтесь на канал, есть видео.
0:56
Александр Маляр
Рет қаралды 4,4 МЛН
Доброта этой девочки.. #shorts
0:31
Only Shorts
Рет қаралды 3,5 МЛН
World’s Largest Jello Pool
1:00
Mark Rober
Рет қаралды 99 МЛН
Bro didn’t make it 😬😟💀 (FAKE NOT REAL) #shorts
0:19
Nate Nahhh
Рет қаралды 11 МЛН
Необычное растение! 😱🌿
0:27
Взрывная История
Рет қаралды 4,1 МЛН
UNO!
0:18
БРУНО
Рет қаралды 1,1 МЛН