ビュー(/show.blade.php)
use App\Http\Controllers\CartController;
$quantity = Stock::where('post_id', $post->id)
->sum('quantity');
if($quantity > 9){
$quantity = 9;
}
<form method="post" action="{{ route('cart.add')}}">
@csrf
<div class="flex items-center">
<select name="quantity class="">
<span class="mr-3">数量</span>
<div class="relative">
@for($i = 1; #i <=$quantity; $i++)
<option value="{{$i}}">{{$i}}</option>
@endfor
</select>
</div>
</div>
<button>カートに追加</button>
<input type="hidden" name="post_id" value="{{ $post>id}}">
</form>
@if(count($posts) > 0)
@foreach($posts as $post)
<div>画像</div>
<div>{{ $post->name }}</div>
<div>{{ $post->pivot->quantity}}</div>
<div>{{ number_format($post->pivot->quantity * $post-
>price )}}円(税込)</div>
@endforeach
合計金額: {{ $totalPrice }}
@else
カートに商品が入っていません。
@endif
ルート
Route::post('add', [CartController::class, 'add'])->name('cart.add');
Route::get(ʻ/', [CartController::class, ʻindex'])->name('cart.index');
php artisan make:model Cart -m
Schema::create('carts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->foreignId('post_id');
$table->integer('quantity');
$table->timestamps();
});
モデル
protected $fillable = [
'user_id',
'post_id',
'quantity',
];
リレーション
Userモデル
use App\Models\Post;
public function posts()
{
return $this->belongsToMany(Post::class, 'carts')
->withPivot(['id', 'quantity']);
// 第2引数で中間テーブル名
// 中間テーブルのカラム取得
Postモデル
use App\Models\User;
public function users()
{
return $this->belongsToMany(User::class,
'carts')
->withPivot(['id', 'quantity']);
}
コントローラ
php artisan make:controller CartController
use App\Models\Cart;
useApp\Models\User;
use Illuminate\Supoort\Facedes\Auth;
public function index(){
$user = User::findOrFail(Auth::id());
$posts = $user->posts; // 多対多のリレーション
$totalPrice = 0;
foreach($posts as $post){
$totalPrice += $post->price * $post->pivot->quantity;
}
//dd($posts,$totalPrice);
return view('cart.index',compact('posts','totalPrice'));
}
public function add(Request $request)
{
$itemInCart = Cart::where('user_id', Auth::id())
->where('post_id', $request->post_id)->first(); //カートに商品があるか確認
if($itemInCart){
$itemInCart->quantity += $request->quantity; //あれば数量を追加
$itemInCart->save();
} else {
Cart::create([ // なければ新規作成
'user_id' => Auth::id(),
'post_id' => $request->post_id,
'quantity' => $request->quantity
]);
//dd(''テスト);
}
return redirect()->route('cart.index');
}