试图在 Laravel 中获取非对象的属性,即使它存在
Posted
技术标签:
【中文标题】试图在 Laravel 中获取非对象的属性,即使它存在【英文标题】:Trying to get property of non-object in Laravel even when it is present 【发布时间】:2016-05-25 16:48:58 【问题描述】:我正在测试的数据在feed
变量中是这样的
"id": 32,
"user_id": 1,
"target_id": 3,
"feedable_id": 7,
"feedable_type": "review",
"created_at": "2016-05-23 14:18:22",
"updated_at": "2016-05-23 14:18:22",
"feedable":
"id": 7,
"user_id": 1,
"slug_id": 3,
"review": "y this product is so quite?",
"stars": 9,
"created_at": "2016-05-23 14:18:22",
"updated_at": "2016-05-23 14:18:22",
"slug":
"id": 3,
"value": "Quite",
"views": 5,
"user_id": 1,
"category_id": 1,
"created_at": "2016-05-23 14:18:03",
"updated_at": "2016-05-24 12:47:29"
但我无法访问该值:在我看来相当
$feed->feedable->slug->value
Laravel 抛出
Trying to get property of non-object (View: ...
【问题讨论】:
模型上的关系是否正确设置? 是的,关系很好,而且回报很好 【参考方案1】:这是一个 json 变量,因此您需要先对其进行解码,然后再访问该值。使用json_decode
可以解码变量并得到期望值。
Check online.
$json = '
"id": 32,
"user_id": 1,
"target_id": 3,
"feedable_id": 7,
"feedable_type": "review",
"created_at": "2016-05-23 14:18:22",
"updated_at": "2016-05-23 14:18:22",
"feedable":
"id": 7,
"user_id": 1,
"slug_id": 3,
"review": "y this product is so quite?",
"stars": 9,
"created_at": "2016-05-23 14:18:22",
"updated_at": "2016-05-23 14:18:22",
"slug":
"id": 3,
"value": "Quite",
"views": 5,
"user_id": 1,
"category_id": 1,
"created_at": "2016-05-23 14:18:03",
"updated_at": "2016-05-24 12:47:29"
';
$feed = json_decode ($json);
echo $feed->feedable->slug->value; //Quite
【讨论】:
以上是关于试图在 Laravel 中获取非对象的属性,即使它存在的主要内容,如果未能解决你的问题,请参考以下文章