9
7

More than 3 years have passed since last update.

MVCでカート機能3 - Controller編 for Laravel

Last updated at Posted at 2019-12-06

考え方

Modelは単体データの操作を。
Viewは表示処理。
ControllerはViewのデータ処理。

データベース

DBカラム
items : id | name | content | price | quantity | created_at | updated_at | deleted_at
carts : id | user_id | item_id | quantity | created_at | updated_at | deleted_at

ソース

app/Http/Controller/CartController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\facades\Auth;
use App\Cart;

class CartController extends Controller
{
    public function __construct(Cart $cart) {
        $this->cart = $cart;
    }
    public function index() {
        $carts = $this->where('user_id', $auth_id)->get();;
        $subtotals = $this->subtotals($carts);
        $totals = $this->totals($carts);
        return view('cart.index', compact('carts', 'totals', 'subtotals'));
    }
    private function subtotals($carts) {
        $result = 0;
        foreach ($carts as $cart) {
            $result += $cart->subtotal();
        }
        return $result;
    }
    private function totals($carts) {
        $result = $this->subtotals($carts) + $this->tax($carts);
        return $result;
    }
    private function tax($carts) {
        $result = floor($this->subtotals($carts) * 0.1);
        return $result;
    }
    public function add(Request $request) {
        $item_id = $request->input('item_id');
        if ($this->cart->insert($item_id, 1)) {
            return redirect(route('cart.index'))->with('true_message', '商品をカートに入れました。');
        } else {
            return redirect(route('cart.index'))->with('false_message', '在庫が足りません。');
        }
    }
    public function delete(Request $request) {
        $cart_id = $request->input('cart_id');
        return redirect(route('cart.index'))->with('true_message', 'カートから商品を削除しました。');
    }
}

解説

set_message(); はオリジナルのヘルパ関数。
sessionに値を挿入して1回だけフラッシュメッセージを出す。
layoutで処理。

メソッド

view からのボタン操作。
・add
・delete
view への表示用。
・index
--private
・subtotals
・tax
・totals

LGTMよろしくお願いします!
励みになります!

9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7