Home > Software design >  HasMany with pluck - does not exist on this collection instance
HasMany with pluck - does not exist on this collection instance

Time:12-12

My Model:

public function colors(): \Illuminate\Database\Eloquent\Relations\HasMany
{
    return $this->hasMany('App\Models\ProductMeta')->where('type', 'content')->where('key', 'color');
}

My Controller:

$watchlist_products = Product::whereIn('id', $watchlist_ids)->colors->pluck('value')->toArray();

It returns:

Property [colors] does not exist on this collection instance.

I can not return colors with any of that? Whats wrong with that?

CodePudding user response:

Because Product::whereIn('id', $watchlist_ids) return more than one product, you can not call ->colors() method on it. the question is colors of which product?

You can get the above result in different ways

For example one way is:

$result = ProductMeta::whereIn('product_id', $watchlist_ids)
->where('type', 'content')
->where('key', 'color')
->pluck('value')
->toArray();

Another way is eager loading the colors on product collection and using dot notation in the ->pluck() method

$products = Product::whereIn('id', $watchlist_ids)->with('colors')->get();
$result = $products->pluck('colors.*.value')->flatten()->toArray();

CodePudding user response:

You are missing a get() before the relation colors

$watchlist_products = Product::whereIn('id', $watchlist_ids)->get()->colors->pluck('value')->toArray();
  • Related