0
votes

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.

2

2 Answers

2
votes

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'))
];
2
votes

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.