添加商品至购物车时出现Call to a member function where() on array错误求助
问题解决:Call to a member function where() on array
问题说明
添加商品至购物车时触发错误:Call to a member function where() on array,错误出现在CartService.php的has()方法中调用$this->cart->where()时。
问题根源
$this->cart是普通PHP数组,而非Laravel Eloquent集合。数组无法调用where()、firstWhere()这类集合专属方法——这才是报错的核心原因,和函数是否包含return语句无关。
解决方案
方案1:将$this->cart转换为Eloquent集合
在CartService的构造函数或初始化$this->cart的位置,使用collect()将数组转为集合:
// 示例:构造函数中初始化购物车数据 public function __construct() { // 假设$cartData是从Session/数据库获取的数组数据 $cartData = session()->get('cart', []); $this->cart = collect($cartData); }
转换后,原有的has()方法代码无需修改,集合可正常调用where()和firstWhere()方法。
方案2:保留数组类型,改用数组函数实现逻辑
如果需要保持$this->cart为数组,修改has()方法,用array_filter()替代集合方法:
public function has($key) { if($key instanceof Model) { $targetId = $key->id; $targetType = get_class($key); $matchedItems = array_filter($this->cart, function($item) use ($targetId, $targetType) { return $item['subject_id'] === $targetId && $item['subject_type'] === $targetType; }); return !empty($matchedItems); } $matchedItems = array_filter($this->cart, function($item) use ($key) { return $item['id'] === $key; }); return !empty($matchedItems); }
补充说明
优先推荐方案1,Laravel集合提供了更简洁的链式操作API,更符合框架开发习惯,后续扩展购物车功能也更便捷。
内容的提问来源于stack exchange,提问作者Mahmoud Khosravi
相关产品推荐
相关产品推荐

