【发布时间】:2015-09-17 07:09:17
【问题描述】:
此应用程序可让您创建产品报价。但是,当他们试图从购物车中删除商品时,会出现以下错误:
[2015-06-29 20:58:28] 生产。错误:异常'ErrorException' 在 /app/controllers/CustomQuoteController.php:613 中带有消息“尝试获取非对象的属性”
#0 /app/controllers/CustomQuoteController.php(613): Illuminate\Exception\Handler->handleError(8, '尝试获取 p...', '/var/www/...', 613, 数组)
我删除了部分路径名。
第 613 行是 if($item_in_cart->name == $custom_quote_item->name)
public function removeFromQuote()
{
$item_exists = true;
$custom_quote_item = CustomQuoteItem::find(Input::get('id'));
$custom_quote_items = Session::get('custom_quote_items');
if(count($custom_quote_items) > 0 )
{
foreach($custom_quote_items as $key => $item_in_cart)
{
// line 613 below
if($item_in_cart->name == $custom_quote_item->name)
{
unset($custom_quote_items[$key]);
Session::set('custom_quote_items', $custom_quote_items);
return Redirect::back()->with('success', 'Item has been removed.');
}
}
}
return Redirect::back()->with('errors', 'Item was not removed.');
}
【问题讨论】:
-
$custom_quote_items是什么类型?我猜它是一个 \Illuminate\Support\Collection 而不是一个数组,所以if(count($custom_quote_items) > 0 )不起作用,它应该是if( ! $custom_quote_items->isEmpty() )。 -
@Quasdunk,这是不正确的。 Laravel 的集合支持数组访问,使用
count($collection)就可以了。 Collections 上还有一个$collection->count()方法可供他使用。 -
@SteveBauman 是的,你是对的!但我记得在 L4.0 中遇到了一个问题,我花了很长时间发现对 Collection 的计数不起作用。但是要么我记错了,要么在以后的版本中修复了:)无论如何,感谢您指出!
-
它是一个数组。我继承了对此的支持,因此了解他们做了什么以及找出问题所在。在这个控制器中发布整个代码会有帮助吗?
-
那么
$item_in_cart或$custom_quote_item是null。你能发布dd($custom_quote_item, $custom_quote_items);的输出吗?并确保CustomQuoteItem::find(Input::get('id'));返回一些东西。你可能想做CustomQuoteItem::findOrFail(...);