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

MahmoudAdelAli's avatar

Find a id of nested relation

Hi , i have laravel e-commerce with customer table and order table and order_details table

the customer has many orders and each order has a order_details

i want when a user enter the product view - if he order this product before he got a link to review it so now i want to get order_details id to send it with this link so i write this code

  auth('customer')->user()->orders()->whereHas('details',function ($q) use ($product){
            $q->where('product_id',$product->id);
        })->get()->first()->details

but i think it's very complex and not professional , so any solutions ?

Order Table

id
customer_id
customer_type
payment_status
order_status
payment_method
transaction_ref
payment_by
payment_note
order_amount
admin_commission
is_pause
cause
shipping_address
created_at
updated_at
discount_amount
discount_type
coupon_code
coupon_discount_bearer
shipping_method_id
shipping_cost
order_group_id
verification_code
seller_id
seller_is
shipping_address_data
delivery_man_id
deliveryman_charge
expected_delivery_date
order_note
billing_address
billing_address_data
order_type
extra_discount
extra_discount_type
checked
shipping_type
delivery_type
delivery_service_name
third_party_delivery_tracking_id

Order Details Table

id
order_id
product_id
seller_id
digital_file_after_sell
product_details
qty
price
tax
discount
tax_model
delivery_status
payment_status
created_at
updated_at
shipping_method_id
variant
variation
discount_type
is_stock_decreased
refund_request
0 likes
3 replies
vincent15000's avatar

Try this.

$details = Detail::whereHas('order', function ($query) {
	$query->where('user_id', auth()->user()->id);
})->where('product_id', $product->id)->first();
1 like
MahmoudAdelAli's avatar
MahmoudAdelAli
OP
Best Answer
Level 5

@PovilasKorop I found a better solution

#User Model
 public function orderDetails()
    {
        return $this->hasManyThrough(OrderDetail::class, Order::class,'customer_id');
    }

And

auth('customer')->user()->orderDetails->where('product_id',$product->id)
1 like

Please or to participate in this conversation.