i want to display the product_name from the other table that has the same product_id laravel

70 views Asked by At

Controller:

public function OrderHistory(){

    $user_id = Auth::User()->id;
    $orders = Order::with('ordersz')->where('user_id',$user_id)->get();
    return view('users.order_history')->with(compact('orders'));
}

Blade page:

<table id="example" class="table table-striped table-bordered" style="width:100%;">
    <thead>
        <tr>
            <th>Order ID</th>
            {{--<th>Quantity</th>--}}
            <th>Ordered Products</th>
            <th> Quantity</th>
            <th>Total</th>
            <th>Order Date</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach($orders as $order)
            <tr>
                <td>{{$order->id}}</td>
                <td>
                    {{--@foreach($userCart as $cart)--}}
                        {{--{{$cart->product_name}}<br>--}}
                    {{--@endforeach--}}

                    @foreach($order->ordersz as $pro)
                        {{$pro->product_id}}<br>// here im displaying the product_id but i want the product name
                    @endforeach
                </td>
                <td>
                    {{--@foreach($userCart as $cart)--}}
                    {{--{{$cart->product_name}}<br>--}}
                    {{--@endforeach--}}

                    @foreach($order->ordersz as $pro)
                        {{$pro->quantity}}<br>
                    @endforeach
                </td>
                <td> {{$order->total_amount}}</td>
                <td> {{$order->created_at}}</td>
                <td>View Details</td>

            </tr>
        @endforeach
    </tbody>
</table>

I'm getting the orders history by user id and I'm displaying the product_id in the orders_product table. Now I want to display the product_name from products table, I have foreign key for products_id

2

There are 2 answers

2
Salah On

Be sure to define the needed relationships within your Order model:

function product() {
    return $this->hasOne('App\Product');
}

Obviously, this implies you have a model for Product, what you should have.

Then within your view you may retrieve your product like follow, thank to dynamic properties:

$pro->product->name;
3
Alex Harris On

If you have a relation on Orderz called product its fairly simple.

Where you eager load orderz you want to add products like so:

$orders = Order::with('ordersz.product')->where('user_id',$user_id)->get();

and then in the blade on the line with your comment you would just do:

{{$pro->product->name}}<br>