Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rpmcmurphy's avatar

Eloquent collection- add extra custom parameter with custom query

I have a products table. Would like to attach related product IDs with an extra collection attr related_ids, which will will a custom query (maybe?). So far I have this-

    $product = Product::where('id', $id)->first()->toArray();
    $related_products = Product::where('id', '!=', $id)->where('category_id', $product['category_id'])->inRandomOrder()->limit(6)->get('id')->map(function($item) {
        return $item->id;
    });
    $product['related_products'] = $related_products;

Any way to do this is one query? I will need this in two place, for single product query, or a list of queried products, like a returned collection but for each product, the related ids will be attached on an extra attribute. Tried this but doesn't work when a new param is added-

    $products = Product::where('author', 'randal')
        ->orderBy('id', 'ASC')
        ->paginate($per_page);
    $products->getCollection()->transform(function ($product) {
        $related_products = Product::where('id', '!=', $product->id)->where('category_id', $product->category_id)->inRandomOrder()->limit(6)->get('id')->map(function ($item) {
            return $item->id;
        });
        $product->related_products = $related_products;
        return $product;
    });

$product->related_products attribute is not appended into the collection at all. Please note that It would be nice if this extra param can be pushed in both for single product query or multiple(for each).

Thanks!

0 likes
2 replies
vincent15000's avatar

You can for example create an appended $related_products property on my Product model to have this property everytime in all your Product models.

protected $appends = ['related_products'];
...
function getRelatedProductsAttribute()
{
        return Product::where('id', '!=', $this->id)->where('category_id', $this->category_id)->inRandomOrder()->limit(6)->get('id')->map(function ($item) {
            return $item->id;
        });
}

And then I could access to the related products as simple as this : $product->related_products.

1 like
rpmcmurphy's avatar

@vincent15000 Yes. This works too. But it runs on every query which is a bit heavy on the database (maybe?). I need the related part on some routes only, not all. Also, I found out that my second code snippet works fine now, attaching related ids on items of collection. Any idea on something similar if I am quering single product?

1 like

Please or to participate in this conversation.