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

shiro_'s avatar

Eloquent Query Nested relationships

I am writing a query to get the correct product_id where $stock->orderProduct->product->generic_name is equal to $item.

My relationships are:

class Stock extends Miioj
{
    public function orderProduct()
    {
        return $this->belongsTo(OrderProduct::class, 'order_product_id', 'id');
    }
class OrderProduct extends Miioj
{
    public function product()
    {
    return $this->belongsTo(Product::class, 'product_id', 'id');
    }
}

My code is as follows, but i keep getting an empty response. Any tips on what i am doing wrong will be highly appreciated.

$item = 'ABZ TAB ABZ TAB';

         $order_product = Stock::whereHas('orderProduct.product', function ($query) use ($item) {
            $query->where('generic_name', $item);
        })->with('orderProduct.product')->pluck('id')->first();

return $order_product;
0 likes
5 replies
MichalOravec's avatar

Do you have ABZ TAB ABZ TAB in generic_name column of products table?

shiro_'s avatar
shiro_
OP
Best Answer
Level 1

My error was because i was querying a non existent column in the table. My code now looks like this :

$stock = Stock::whereHas('orderProduct.product') 
                ->where('orderProduct.product.generic_name', $item)
                ->with(['orderProduct.product.price' => function ($query) use ($paymentMode) {
                    $query->where('scheme_id', $paymentMode->scheme_id);
                }])->first();
shiro_'s avatar

Actually no, maybe whereNotNull

Please or to participate in this conversation.