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

lastpeony's avatar

Fetching and Displaying Customer Orders on Page

There are 3 tables. First one is orders:

After example order:

enter image description here

class Order extends Model
{
   // Table Name
   protected $table = 'orders';

   // Primary Key
   public $primaryKey = 'id';

   // Timestamps
   public $timestamps = true;

   public function user() {         
       return $this->belongsTo('App\User');   
   }

   public function orderproduct() {
       return $this->hasMany('App\OrderProduct');
   }
}

Second one is OrderProduct table:

enter image description here

class OrderProduct extends Model
{
    // Table Name
    protected $table = 'order_product';

    // Primary Key
    public $primaryKey = 'id';

    // Timestamps
    public $timestamps = true;

    public function order() {
        return $this->belongsTo('App\Order');   
    }

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

Third one is products table:

enter image description here

class Product extends Model
{
    // Table Name
    protected $table = 'products';

    // Primary Key
    public $primaryKey = 'id';

    // Timestamps
    public $timestamps = true;

    public function orderproduct() {
        return $this->belongsTo('App\OrderProduct');
    }
}

What I am trying to do is: after user places an order, how do I write the correct eloquent query to display the order user has placed with the product he ordered? I mean I am redirecting user to their orders page after they place an order, right there I want to show their order details.

I reach user id with this: auth()->user()->id Now with using this id i can reach order_date from first table. Orders id is foreign key (order_id) in orderproduct table.

From second table take quantity and using product_id in second table reach information of product(name,img,price...)

So in the end i would like to display Order ID Ordered Products Name Ordered Products Img Quantity of product ordered Order Date Paid Money(Quantity x price)

0 likes
7 replies
Sys32's avatar

This will not work, as you cannot identify the individual product, with its parent orderproduct, unless you specify that within the table, which shouldnt be done as products are used globally in the application.

public function orderproduct() {
    return $this->belongsTo('App\OrderProduct');
}

Anyway, I believe the code below should work for displaying the order.

First rename this from orderproduct to OrderProducts.

public function orderproduct() {
   return $this->hasMany('App\OrderProduct');
}

Second rename this from product to Product, its just cosmetic but makes it easy to see what is a relation, and what is a field

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

After that is done, you should be able to list the products using the code below.

public function viewOrder($orderid) {
    $order = Order::findOrFail($orderid);

    if ($order->customer_id != Auth::user()->id) {
        return abort(401);
    }

    return view('orderview', ['order' => $order]);
}

In the view you add this

<table style="width:100%">
    <tr>
        <th>Product</th>
        <th>Desc</th> 
        <th>Quantity</th>
    </tr>

    @foreach ($order->OrderProducts as $orderProduct) 
    <tr>
        <td>{{ $orderProduct->Product->name }}</td>
        <td>{{ $orderProduct->Product->desc }}</td> 
        <td>{{ $orderProduct->quantity }}</td>
    </tr>
    @endforeach

</table>
lastpeony's avatar

Hello i got this error: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.order_product_id' in 'where clause' (SQL: select * from products where products.order_product_id = 1 and products.order_product_id is not null) (View: C:\xampp\htdocs\ecommerce\resources\views\userorders.blade.php) ◀"

By the way thanks for the answer but i couldnt really understand modals part which modal should i exactly change and how ?

Vilfago's avatar

OrderProduct table should be considered as a pivot table in a many-to-many relationship. I think it's far more easier to handle it this way.

I cannot detail you the code right now, but I will do it later if needed.

Vilfago's avatar
Vilfago
Best Answer
Level 20

If I understood well.

  • Each Order is related to one customer, and ( to ) each customer can have many Orders - (One-to-Many relationship)
  • Each Order can have many Products and ( to ) each Product can be assigned to many Orders - (Many-to-Many relationship).

We found 3 Models :

  • Customer
  • Order
  • Product

So let's try to build it :

class Customer extends Model
{
    protected $table = 'customers';
    //[...]

    public function orders()
    {
        return $this->hasMany('App\Order');
    }
}


class Order extends Model
{
    protected $table = 'orders';
    //[...]

    public function user()
    {         
        return $this->belongsTo('App\User');   
     }

    public function products()
    {
        return $this->belongsToMany('App\Product', 'OrderProduct')
                ->withPivot('quantity')
                ->withTimestamps();
        /**
        * 2nd argument is the name of the pivot table
        * the pivot table is the table which can link your two tables
        * Eloquent expect that the name is order_product
        * as it's not the case, we specify its name
        *
        * withPivot('quantity') tells that you don't only have
        * order_id and product_id on this table, but you want to
        * manage the quantity column too.
        *
        * withTimestamps() instruct Eloquent that you want he
        * automatically handle the columns "created_at" and "updated_at"
        * as for a standard table.
        */
    }
}

class Product extends Model
{
    protected $table = 'products';
    //[...]
    
    public function orders()
    {
        return $this->belongsToMany('App\Order', 'OrderProduct')
                ->withPivot('quantity')
                ->withTimestamps(); //same comment as above
    }
}

And now, you can have a try :

echo 'Load all orders of one customer';
$customer = Customer::with('orders')->find($customer_id);
dump($customer);

echo 'Load all products of one order';
$order = Order::with('products')->findOrFail($order_id);
dump($order);

echo 'Load all orders on which a specific product was ordered';
$product = Product::with('orders')->findOrFail($product_id);
dump($product);

echo 'Load all orders of one customer, with all related products, as we have no time to loose';
$customer_speed = Customer::with('orders.products')->find($customer_id);
dump($customer_speed);

echo 'Finally, I want all my database, but clearly ordered... and die because it was too much !';
$everything = Customer::with('orders.products')->get();
dd($everything);

Everything come from : https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

Read carefully : Defining Custom Intermediate Table Models if you want to do more things on your pivot table, and you need a model for that.

And read also : https://laravel.com/docs/5.6/eloquent-relationships#updating-many-to-many-relationships to know how insert or update this relation, as I didn't cover that in this post.

I hope it helps !

1 like
Vilfago's avatar

With pleasure,

You can make this thread resolved (tick "best answer").

1 like

Please or to participate in this conversation.