選択可能な数量を制限する方法

各商品にはstockのような属性があると仮定します。このstock属性は商品の在庫数を表します。
商品の詳細ページに遷移したとき、stock属性を使用して、選択できる数量を制限します。
在庫が0の場合、カートに入れるボタンを無効化し、「現在在庫が切れています。入荷までお待ち下さい」というメッセージを表示します。

$post->stockという属性が実際のデータベースやモデルに存在している条件で説明します。

○数量のプルダウンメニュー
<!-- 数量のプルダウンメニュー -->

<form action="/purchase/{{ $post->id }}" method="post">
    @csrf
    <div class="mt-4 mb-2">
        <label for="quantity" class="mr-2">数量:</label>
        @if ($post->stock > 0)
            <select id="quantity" name="quantity" class="rounded-xl">
                @for ($i = 1; $i <= $post->stock; $i++)
                    <option value="{{ $i }}">{{ $i }}</option>
                @endfor
            </select>
            <button type="submit">購入</button>
        @else
            <p class="text-red-500 mt-2">現在在庫が切れています。入荷までお待ち下さい。</p>
        @endif
    </div>
</form>

 


○カートに入れるボタンを無効化
<!-- カートに入れるボタン -->
@if ($post->stock > 0)
    <x-primary-button class="bg-transparent hover:bg-yellow-200 text-yellow-200 font-semibold hover:text-white py-2 px-4 border-2 border-yellow-200 hover:border-transparent rounded-xl float-right">
        カートに入れる
    </x-primary-button>
@else
    <x-primary-button class="bg-gray-200 cursor-not-allowed text-gray-500 font-semibold py-2 px-4 border-2 border-gray-300 rounded-xl float-right" disabled>
        カートに入れる
    </x-primary-button>
@endif

○カートに入れるボタンを無効化【sprite】

①ボタンのクリックイベントリスナー内で在庫数を確認し、在庫が0の場合はStripeの支払いページにリダイレクトしないようにします。

<script>
 var stock = {{ $post->stock }};
    ...

checkoutButton.addEventListener('click', function(event) {
    if (stock <= 0) {
        event.preventDefault(); // ボタンのデフォルトの動作をキャンセル
        displayError.textContent = "在庫がありません。";
        return; // 処理を終了
    }

    stripe.redirectToCheckout({sessionId: "{{ $session->id }}"})
    .then(function (result) {
        if (result.error) {
            console.log(result.error);
        }
    });
});

</script>

②また、在庫が0の場合にボタンを無効化するというUI的なアプローチも取ることができます。

<button id="checkout-button" class="text-white text-xl font-semibold bg-blue-700
hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 font-medium rounded-full
text-sm px-5 py-2.5 text-center mr-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700
dark:focus:ring-blue-800" {{ $post->stock <= 0 ? 'disabled' : '' }}>購入ボタン</button>


○商品が売れる度にstockを減少させる

use Illuminate\Http\Request;

public function purchase(Request $request, Post $post)
{
    // 選択された数量を取得
    $selectedQuantity = $request->input('quantity');

    // 在庫を選択された数量だけ減少させる
    $post->decrement('stock', $selectedQuantity);

    // ... その他の処理 ...

    return redirect()->back()->with('message', '購入しました!');
}

○商品が売れる度にstockを減少させる【stripe】

// StripeController.php

public function start() {
    $stripe = new \Stripe\StripeClient(config('services.stripe.st_key'));
    $url = 'http://127.0.0.1:8000';
    $userId = auth()->user()->id;
    $postId = $post->id;

 

use App\Models\Post;  // Postモデルを使うので追加

public function success(Request $request, $userId, $postId) {
    // ユーザー情報の更新
    $user = User::find($userId);
    // 商品の在庫を減少
    $post = Post::find($postId);
    $selectedQuantity = $request->input('quantity');
    if ($post && $post->stock >= $selectedQuantity) {
        $post->decrement('stock', $selectedQuantity);
    }