-1

I have a carts table where column is----> "id", "user_id", "product_id", "quantity". See the image carts table image

here is ther products table products table

When a user add item into cart ,I want to get total price of products which is added into cart by the user. How to do that?

Here is the cart model cart model

Here is the product model product model

Chandan
  • 11,465
  • 1
  • 6
  • 25
Prince
  • 39
  • 8

1 Answers1

0

One option:

You can edit the existing relationship or create a new relationship for Cart in the User model to join the products table and do a calculation to get the total price.

//User model
public function cartsWithProductPrice(){
 return $this->hasMany(Cart::class)
             ->join('products', 'carts.product_id', 'products.id')
             ->select('carts.*', 
                      \DB::raw('carts.quantity * products.price as price')
                     );
}

And when you call for example User::with('cartsWithProductPrice')->find(1); it should give you the cart relationship with a field named price with total price.

Hope that this will point you in the right direction.

user3532758
  • 2,221
  • 1
  • 12
  • 17