CartController.php

   public function success(){
        $carts = Cart::where('user_id', auth()->user()->id)->get();
        $user = auth()->user();
        $firstAddress = $user->addresses()->first();

        if (!$firstAddress) {
        // 住所が登録されていない場合の処理
        }

        $order = Order::create([
                'user_id' => $user->id,
                'address_id' =>$firstAddress->id,
            ]);

        $total = 0; // 合計金額
        $orderItems = []; // 注文アイテムの情報を格納する配列

           // カート内のアイテムを処理
        foreach ($carts as $cart) {
            $post = $cart->post;
            $subtotal = $post->price * $cart->quantity;
            $total += $subtotal;

            OrderItem::create([
                'order_id' => $order->id,
                'post_id' => $cart->post_id,
                'quantity' => $cart->quantity,
            ]);

            array_push($orderItems, [
                'title' => $post->title,
                'quantity' => $cart->quantity,
                'price' => $post->price,
                'subtotal' => $subtotal
            ]);
        }

        $order_info = [
            'user' => $user,
            'address' => $firstAddress,
            'orderItems' => $orderItems,
            'total' => $total,
        ];


        // 購入者に「注文内容ご確認」メールを送る
        Mail::to($user->email)->send(new \App\Mail\NewOrder($order_info));
        Mail::to('xxx.com')->send(new \App\Mail\NewOrder($order_info));

        Cart::where('user_id', auth()->user()->id)->delete();

        return redirect()->route('post.index')->with('message',
'支払いが完了しました。');
    }

    public function cancel(){
        $carts = Cart::where('user_id', auth()->user()->id)->get();

        foreach($carts as $cart){
            $post = Post::find($cart->post_id);
            $quantity = $cart->quantity;
            $post->increment('stock', $quantity);
        }
        return redirect()->route('cart.index')->with('message',
'支払いが取り消されました。');;
 
 
 
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Cart extends Model
{
    use HasFactory;
    protected $fillable = [
        'user_id',
        'post_id',
        'quantity',
    ];

    public function post()
    {
        return $this->belongsTo(Post::class, 'post_id');
    }
}
 
 
//cart/index.blade.php
<x-app-layout>
      <x-slot name="header">
        <h2>
            カート
        </h2>
        {{-- @if(session('message'))
            {{session('message')}}
        @endif --}}
        {{-- <x-input-error class="mb-4" :messages="$errors->all()"/> --}}
        <x-validation-errors class="mb-4" :errors="$errors" />
        <x-message :message="session('message')" />
    </x-slot>

  <div class="py-12">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
          <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
              <div class="p-6 bg-white border-b border-gray-200">
                  @if (count($carts) > 0)
                    @foreach ($carts as $cart )
                      <div class="md:flex md:items-center mb-2">
                        <div class="md:w-3/12">
                          @if ($cart->post->image !== null)
                          <img src="{{ asset('storage/images/
'.$cart->post->image)}}">
                          @else
                          <img src="">
                          @endif
                        </div>
                        <div class="md:w-4/12 md:ml-2">
{{ $cart->post->title }}</div>
                        <div class="md:w-3/12 flex justify-around">
                          <div>{{ $cart->quantity }}冊</div>
                          <div>{{ number_format($cart->quantity
* $cart->post->price )}}
<span class="text-sm text-gray-700">円(税込)</span>
</div>
                        </div>
                        <div class="md:w-2/12">
                          <form method="post" action="{{route('cart.delete',
['item' => $cart->post->id ])}}">
                            @csrf
                            <button>
                              <svg xmlns="http://www.w3.org/2000/svg" fill="none"
viewBox="0 0 24 24" stroke-width="1.5"
stroke="currentColor" class="w-6 h-6">
                                <path stroke-linecap="round"
stroke-linejoin="round"
                              </svg>
                            </button>
                          </form>
                        </div>
                      </div>
                    @endforeach
                    <div class="my-2">
                      小計: {{ number_format($totalPrice)}}
<span class="text-sm text-gray-700">円(税込)</span>
                    </div>
                    <div>
                      {{-- <button onclick="location.href=
'{{ route('cart.checkout')}}'">購入する
                      </button> --}}
                      <button onclick="checkAddressAndProceed()">購入する
                      </button>

                    </div>
                  @else
                    カートに商品が入っていません。
                  @endif
              </div>
          </div>
      </div>
  </div>
    <script>
        function checkAddressAndProceed() {
            @php
                $user = auth()->user();
                $hasAddress = $user->addresses()->exists();
            @endphp

            @if (!$hasAddress)
                alert('送り先住所をアカウント設定画面で登録
してからご注文ください。');
                window.location.href = "{{ route('profile.edit') }}";
            @else
                window.location.href = "{{ route('cart.checkout') }}";
            @endif
        }
    </script>
</x-app-layout>