Norgul
Norgul

Reputation: 4783

Laravel eager load resource collection

How can I eager load a resource collection relationship? I've made a resource which calls gravel_pits relationship

class GravelTypeResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id'          => $this->id,
            'name'        => $this->name,
            'deleted_at'  => $this->deleted_at,
            'gravel_pits' => $this->gravel_pits,
        ];
    }
}

On the model M:M relationship:

public function gravel_pits()
{
    return $this->belongsToMany('App\GravelPit');
}

And from the API I am getting it back like this:

public function index()
{
    return GravelTypeResource::collection(GravelType::all());
}

I can eager load it by doing

public function index()
{
    return GravelTypeResource::collection(GravelType::with('gravel_pits'));
}

which works...but I can't control then what properties of gravel pits I actually want back, instead, eager load fetches them all. Is there a simple workaround to this?

Upvotes: 1

Views: 5477

Answers (2)

Ahmed Aboud
Ahmed Aboud

Reputation: 1322

you can use Resource Collections

GravelTypeResourceCollection::make($collection);

and since you can use load and loadMissing on eloquent collections you can do this

class GravelTypeResourceCollection extends ResourceCollection
{
   $collects = GravelTypeResource::class;

   public function __construct($resource){
        $resource->loadMissing(['gravel_pits']);
        parent::__construct($resource);
    }
}

Upvotes: 2

aynber
aynber

Reputation: 23011

You can pass in a select to get just the fields you want. Just make sure you get the fields that the relationship is based on:

return GravelTypeResource::collection(GravelType::with('gravel_pits'=>function($query) {
     $query->select(['id', 'gravel_type_id', 'column3', 'column4']);
});

Upvotes: 0

Related Questions