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

Stelikas's avatar

Get ID of model inside eloquent query

Is there any way to get the ID inside the query?

I don't know how to explain this fluently, but I'm trying to grab the product options for each product, but i need to use the product ID inside the with statement to do that.

Something like that but $idOfModel should obviously be the id of each product.

$product = $product->with('attributes', function($q) {
            $q->with('product_options', function($q) {
                $q->where('product_id', $idOfModel)->with('variable', function($q) {
                    $q->where('product_id', $idOfModel);
                });
            })->groupBy('id');
        })->take(10)->get();
0 likes
1 reply
MohamedTammam's avatar

If you have your relationship between modals it will be used automatically. You don't need that part.

$q->where('product_id', $idOfModel)

Please or to participate in this conversation.