Laravel Multi level relationship in API Resource

My problem is, the api resource loading which i really not needed.
Look into my Api Resource files

//BoxItemResource.php

 public function toArray($request)
{
    return [
        'box_id'=> $this->box_id,
        'item_id'=> $this->item_id,
        'item'=> new ItemResource($this->item)
    ];
}

//ItemResource.php
public function toArray($request)
{
    return [
        'id' => $this->id,
        'shipping_price' => $this->shipping_price,
        'condition_id' => $this->condition_id,
        'condition' => new ConditionResource($this->condition)
    ];
}

//ConditionResource.php
public function toArray($request)
{
    return [
        'id'=> $this->id,
        'name'=> $this->name
    ];
}

//controller
return BoxItemResource::collection(
        BoxItem::with([
            'item'
        ])->paginate(1)
    );

My problem is, I just need only BoxItem and Item here. I don’t really want to load condition.
If i remove the condition relation from ItemResource.php, it will work. but the problem is I am using the ItemResource.php in some other place which need this condition.

Is it possible to deny loading condition relation ship here.

more clearly, I want to load the relationship which I mention in controller(in ->with()) .

Thanks in advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

API resources allow for conditional attribtues and conditional relationships.

For attributes, which in my opinion is sufficient to use in your case, this means you can simply wrap the attribute value in $this->when($condition, $value) and the whole attribute will be removed from the result if $condition == false. So a concrete example of your code:

return [
    'box_id'=> $this->box_id,
    'item_id'=> $this->item_id,
    'item'=> $this->when($this->relationLoaded('item'), new ItemResource($this->item))
];

Or if you prefer using the relationship style:
return [
    'box_id'=> $this->box_id,
    'item_id'=> $this->item_id,
    'item'=> new ItemResource($this->whenLoaded('item'))
];

Method 2

Maybe you are looking for Conditional Relationships?

Ideally, it should look like the following:

public function toArray($request)
{
    return [
        'box_id'=> $this->box_id,
        'item' => ItemResource::collection($this->whenLoaded('item'))
    ];
}

The item key will only be present if the relationship has been loaded.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x