【问题标题】:Laravel - 'ErrorException' with message 'Trying to get property of non-object'Laravel - 带有消息“尝试获取非对象的属性”的“ErrorException”
【发布时间】: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_itemnull。你能发布dd($custom_quote_item, $custom_quote_items); 的输出吗?并确保CustomQuoteItem::find(Input::get('id')); 返回一些东西。你可能想做CustomQuoteItem::findOrFail(...);

标签: php laravel


【解决方案1】:

由于您在第 613 行检索 $item_in_cart$custom_quote_item 的属性,这就是您的问题所在。其中一个不是对象,或者不包含属性name,如异常所述。

我会使用dd($item_in_cart) 验证这两个变量都是对象,并用输出更新我们,我猜$item_in_cart 是问题所在,因为您是从会话中检索它并循环遍历它。

【讨论】:

  • object(CustomQuoteItem)[99] protected 'guarded' => array (size=0) empty protected 'table' => string 'custom_quote_items' (length=18) public 'price' => string '$0.60' (length=5) protected 'connection' => null protected 'primaryKey' => string 'id' (length=2) protected 'perPage' => int 15 public 'incrementing' => boolean true public 'timestamps' => boolean true protected 'attributes' => array (size=3) 'name' => string '10255.011010' (length=12) 'description' => string '10 x 10 x 1' (length=11) 'quantity ' => 字符串'12.000'(长度=6)
  • 我做了一个 dd ($custom_quote_item);它是空的。所以现在认为它必须是顶部的查找部分。
猜你喜欢
  • 1970-01-01
  • 2017-08-02
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 2020-09-30
  • 1970-01-01
  • 2021-07-19
相关资源
最近更新 更多