Laravel5.5で、ショッピングカートの合計金額を取得です。 いろいろな方法があると思いますが、エレガントな取得方法を見つけました。美しい(笑)。
/app/Cart.php
参考サイト
Laravel Eloquent: Best Way to Calculate Total Price(Stack Overflow)
/app/Cart.php
class Cart extends Model
{
// リレーション
public function item()
{
return $this->belongsToMany('App\Item')->withPivot('quantity');
}
// 合計金額集計
public function getTotalPrice() {
return $this->item()->sum(DB::raw('cart_item.quantity * items.price'));
}
}
参考サイト
Laravel Eloquent: Best Way to Calculate Total Price(Stack Overflow)