You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9购物车报错:Undefined array key 'name' 技术求助

问题排查:Laravel 9购物车报错“Undefined array key 'name'”

问题描述

我正在使用Laravel 9开发电商网站,数据库中有一张名为products的表,使用title字段存储商品名称。已实现购物车的添加、更新、删除功能,但访问购物车路由时出现报错:Undefined array key "name"。

相关代码

CartController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class CartController extends Controller
{
  public function cart()
  {
    return view('cart');
  }

  /**
  * Write code on Method
  *
  * @return response()
  */
  public function addToCart($id)
  {
    $product = Product::findOrFail($id);
    
    $cart = session()->get('cart', []);

    if(isset($cart[$id])) {
        $cart[$id]['quantity']++;
    } else {
        $cart[$id] = [
            "title" => $product->title,
            "quantity" => 1,
            "price" => $product->price,
            "image" => $product->image
        ];
    }
    
    session()->put('cart', $cart);
    return redirect()->back()->with('success', 'Product added to cart successfully!');
  }

  /**
  * Write code on Method
  *
  * @return response()
  */
  public function update(Request $request)
  {
    if($request->id && $request->quantity){
      $cart = session()->get('cart');
      $cart[$request->id]["quantity"] = $request->quantity;
      session()->put('cart', $cart);
      session()->flash('success', 'Cart updated successfully');
    }
  }

  /**
  * Write code on Method
  *
  * @return response()
  */
  public function remove(Request $request)
  {
    if($request->id) {
      $cart = session()->get('cart');
      if(isset($cart[$request->id])) {
          unset($cart[$request->id]);
          session()->put('cart', $cart);
      }
      session()->flash('success', 'Product removed successfully');
    }
  }
}

cart.blade.php

@extends('layout')

@section('content')
<table id="cart" class="table table-hover table-condensed">
 <thead>
  <tr>
<th style="width:50%">Product</th>
<th style="width:10%">Price</th>
<th style="width:8%">Quantity</th>
<th style="width:22%" class="text-center">Subtotal</th>
<th style="width:10%"></th>
        </tr>
    </thead>
   <tbody>
     @php $total = 0 @endphp
      @if(session('cart'))
      @foreach(session('cart') as $id => $details)
       @php $total += $details['price'] * $details['quantity'] @endphp
    <tr data-id="{{ $id }}">
        <td data-th="Product">
            <div class="row">
                <div class="col-sm-3 hidden-xs"><img src="{{ $details['image'] }}" width="100" height="100" class="img-responsive"/></div>
                <div class="col-sm-9">
                    <h4 class="nomargin">{{ $details['name'] }}</h4>
                </div>
            </div>
        </td>
        <td data-th="Price">${{ $details['price'] }}</td>
        <td data-th="Quantity">
            <input type="number" value="{{ $details['quantity'] }}" class="form-control quantity update-cart" />
        </td>
        <td data-th="Subtotal" class="text-center">${{ $details['price'] * $details['quantity'] }}</td>
        <td class="actions" data-th="">
            <button class="btn btn-danger btn-sm remove-from-cart"><i class="fa fa-trash-o"></i></button>
        </td>
    </tr>
@endforeach
       @endif
     </tbody>
    <tfoot>
    <tr>
<th colspan="5" class="text-right"><h3><strong>Total ${{ $total }}</strong></h3></th>
     </tr>
   <tr>
<th colspan="5" class="text-right">
    <a href="{{ url('/') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a>
    <button class="btn btn-success">Checkout</button>
</th>
    </tr>
  </tfoot>
 </table>
@endsection

@section('scripts')
<script type="text/javascript">

$(".update-cart").change(function (e) {
   e.preventDefault();

var ele = $(this);

   $.ajax({
    url: '{{ route('update.cart') }}',
    method: "patch",
    data: {
        _token: '{{ csrf_token() }}', 
        id: ele.parents("tr").attr("data-id"), 
        quantity: ele.parents("tr").find(".quantity").val()
    },
    success: function (response) {
       window.location.reload();
     }
        });
    });

   $(".remove-from-cart").click(function (e) {
  e.preventDefault();

    var ele = $(this);

     if(confirm("Are you sure want to remove?")) {
    $.ajax({
        url: '{{ route('remove.from.cart') }}',
        method: "DELETE",
        data: {
            _token: '{{ csrf_token() }}', 
            id: ele.parents("tr").attr("data-id")
        },
        success: function (response) {
            window.location.reload();
        }
    });
  }
 });

</script>
@endsection

shop.blade.php

<div class="container">
                    <div class="row">
                        <div class="col-lg-12 col-sm-12 col-12 main-section" style="background-color: #3D464D !important">
                            <div class="dropdown">
                                <button type="button" class="btn btn-info" data-toggle="dropdown" style="    margin-top: 26px;
                                margin-left: 54px;
                                background-color: #FFD333 !important">
                                    <i class="fa fa-shopping-cart" aria-hidden="true"></i> Cart <span class="badge badge-pill badge-danger">{{ count((array) session('cart')) }}</span>
                                </button>
                                <div class="dropdown-menu">
                                    <div class="row total-header-section">
                                        <div class="col-lg-6 col-sm-6 col-6">
                                            <i class="fa fa-shopping-cart" aria-hidden="true"></i> <span class="badge badge-pill badge-danger">{{ count((array) session('cart')) }}</span>
                                        </div>
                                        @php $total = 0 @endphp
                                        @foreach((array) session('cart') as $id => $details)
                                            @php $total += $details['price'] * $details['quantity'] @endphp
                                        @endforeach
                                        <div class="col-lg-6 col-sm-6 col-6 total-section text-right">
                                            <p>Total: <span class="text-info">$ {{ $total }}</span></p>
                                        </div>
                                    </div>
                                    @if(session('cart'))
                                        @foreach(session('cart') as $id => $details)
                                            <div class="row cart-detail">
                                                <div class="col-lg-8 col-sm-8 col-8 cart-detail-product">
                                                    <p>{{ $details['title'] }}</p>
                                                    <span class="price text-info"> ${{ $details['price'] }}</span> <span class="count"> Quantity:{{ $details['quantity'] }}</span>
                                                </div>
                                            </div>
                                        @endforeach
                                    @endif
                                    <div class="row">
                                        <div class="col-lg-12 col-sm-12 col-12 text-center checkout">
                                            <a href="{{ route('cart') }}" class="btn btn-primary btn-block">View all</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

错误原因

在CartController.php的addToCart方法中,存入session的购物车数据里使用的键是title(对应商品名称),但在cart.blade.php渲染商品名称时,错误地尝试访问不存在的name键,导致触发数组键未定义的报错。而shop.blade.php中是正确使用$details['title']显示商品名称,这也验证了session数据里只有title键,没有name键。

解决方案

提供两种可选方案,选择其中一种即可:

方案1:修改视图文件(推荐,改动最小)

打开cart.blade.php,找到显示商品名称的行:

<h4 class="nomargin">{{ $details['name'] }}</h4>

将其替换为:

<h4 class="nomargin">{{ $details['title'] }}</h4>

方案2:修改控制器同步键名

打开CartController.php的addToCart方法,修改存入购物车的数组:

  • 可选2.1:添加name键,保留原title键
$cart[$id] = [
    "title" => $product->title,
    "name" => $product->title, // 添加该行
    "quantity" => 1,
    "price" => $product->price,
    "image" => $product->image
];
  • 可选2.2:直接将title键名改为name(需同步修改shop.blade.php)
$cart[$id] = [
    "name" => $product->title, // 修改键名为name
    "quantity" => 1,
    "price" => $product->price,
    "image" => $product->image
];

若选择2.2,需同步修改shop.blade.php中显示商品名称的行:

<p>{{ $details['title'] }}</p>

改为:

<p>{{ $details['name'] }}</p>

内容的提问来源于stack exchange,提问作者rezoia_86

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 00:06:25