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

Sdílet
Vložit
  • čas přidán 19. 06. 2022
  • 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
  • Jak na to + styl

Komentáře • 58

  • @IlPandax
    @IlPandax Před 2 lety +32

    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 Před 2 lety +8

    With conditional resource like when($request->routeIs(`list`)) you may somehow manage to use same resource class for all endpoints

  • @chlouis-girardot
    @chlouis-girardot Před 2 lety +3

    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 !

  • @OnlinePseudonym
    @OnlinePseudonym Před 2 lety +7

    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.

  • @OtiszWasTaken
    @OtiszWasTaken Před 2 lety +6

    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 Před 2 lety +2

      Hello sir, excuse me, can you have some link to the example ? Thanks for the tip

  • @azelen
    @azelen Před 2 lety +1

    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 Před 2 lety +3

    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.

  • @rahulkumarsingh1716
    @rahulkumarsingh1716 Před 2 lety +1

    u can override the constructor to use same resources class for different purpose

  • @nabeelyousafpasha
    @nabeelyousafpasha Před 2 lety +1

    It somehow convinced me to adopt this new idea

  • @kaustubhbagwe6718
    @kaustubhbagwe6718 Před 2 lety +1

    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 Před 2 lety

    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 :)

  • @bboydarknesz
    @bboydarknesz Před 2 lety +1

    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  Před 2 lety

      Good catch, with different classes it's hard to keep consistency, I guess it's just a matter of communication in a team.

  • @ljubicasamardzic7819
    @ljubicasamardzic7819 Před 2 lety +1

    I literally had the same issue a week ago and also opted for separate resources.

  • @PeeNoiseKulangot
    @PeeNoiseKulangot Před rokem

    How about Complex nested Resources with relationships?

  • @5dmat-web
    @5dmat-web Před rokem

    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

  • @SunilYadav-tm6kt
    @SunilYadav-tm6kt Před 2 lety +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  Před 2 lety +2

      That's another way of doing it, yes.

    • @andywong2244
      @andywong2244 Před rokem

      this is interesting. will try this one out. thanks for the idea!

  • @alila3883
    @alila3883 Před 2 lety +1

    I think one resourse best way but inside resourse class use match or switch method to use the correct route…

  • @MrNotsoft
    @MrNotsoft Před 2 lety +1

    Yes, I recently came to the same conclusion. On one's own)

  • @TheBaraa2011
    @TheBaraa2011 Před 2 lety +1

    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;
    }),
    ]

  •  Před 2 lety +1

    How do you solve situation, when you change your model and you need to update all Resources?

    • @LaravelDaily
      @LaravelDaily  Před 2 lety +1

      I update all resources, then. It's a rare occasion and I don't remember creating more than 3 resources per model.

  • @aribiali3574
    @aribiali3574 Před 2 lety

    Thank you a lot 💙

  • @NathanBudd
    @NathanBudd Před 2 lety

    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  Před 2 lety +1

      Normal react, without SSR. That's a course for React beginners, SSR or frameworks are another new level.

  • @mohamadcheaib
    @mohamadcheaib Před 2 lety +1

    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  Před 2 lety +1

      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 Před 2 lety +1

    Also maybe use the helper request inside categories resources and make some conditions? And then reuse original CategoryResource ?

    • @0xshaheen
      @0xshaheen Před 2 lety

      Yes I agree with you

    • @LaravelDaily
      @LaravelDaily  Před 2 lety

      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.

  • @kirayamato6128
    @kirayamato6128 Před 2 lety

    I don't use api resources because it will have am extrea query when performing the controller actions.

  • @intipontt7490
    @intipontt7490 Před 2 lety +1

    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.

  • @jufrensiusbarasa6539
    @jufrensiusbarasa6539 Před 2 lety

    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  Před 2 lety

      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 Před 2 lety

      @@LaravelDaily Thank you for your suggestions

    • @nabeelyousafpasha
      @nabeelyousafpasha Před 2 lety +1

      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

    👍👍👍

  • @thewizardguy1337
    @thewizardguy1337 Před 2 lety

    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  Před 2 lety

      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 Před 2 lety

      @@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  Před 2 lety

      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.

  • @MartinBojmaliev
    @MartinBojmaliev Před 2 lety

    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  Před 2 lety +1

      No, whatever works for you, if you don't need any transformations from the model

  • @ezz_dev
    @ezz_dev Před 14 dny

    the course link says "This product is not avalable"

    • @LaravelDaily
      @LaravelDaily  Před 14 dny

      I've moved my courses in 2022 to my own platform, see laraveldaily.com/courses

  • @user-cf5uf7vf2g
    @user-cf5uf7vf2g Před 2 lety

    agreed with more readability, don't wrap too much layer.

  • @zhgaaaaaan
    @zhgaaaaaan Před 2 lety

    categoriesResources::make() Vs new categoriesResources() ?

  • @bmtamim7818
    @bmtamim7818 Před 2 lety

    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  Před 2 lety

      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 Před 2 lety

      @@LaravelDaily yes, Its run one query per relationship. Is it possible to run only one query?

    • @user-fi1uh8ct2j
      @user-fi1uh8ct2j Před 2 lety

      @@bmtamim7818 you cant with built-in Eloquent ORM behavior.

    • @bmtamim7818
      @bmtamim7818 Před 2 lety

      @@user-fi1uh8ct2j Got it..thanks

    • @bmtamim7818
      @bmtamim7818 Před 2 lety

      @@LaravelDaily Thanks a lot..sir❤️