【发布时间】:2021-04-23 16:12:52
【问题描述】:
我正在 Laravel 8 上运行一个项目,并试图急切加载一些数据。数据按预期获取,但当我尝试将数据显示到刀片时出现问题。
我的控制器
public function siteHome(){
$featuredArticle = Article::with('articleCategory')->first();
return view('site.index', compact('featuredArticle'));
}
正确获取的来自 siteHome() 方法的响应
{
"id": 1,
"title": "politics",
"author": "Andreas",
"status": "published",
"image": "testimage",
"image_caption": "test image",
"category_id": 1,
"article_text": "test article content",
"created_at": null,
"updated_at": null,
"article_category": {
"id": 1,
"name": "Politics",
"created_at": null,
"updated_at": null
}
}
在我的刀片上,我想显示文章表中的作者、状态和图像,并从 article_catgeory 中提取文章类别名称。
在 laravel 7 中,我会通过循环数据提取文章类别名称并获取所有信息并将其显示在刀片中。下面的代码显示了我在 laravel 7 中是如何做到这一点的
foreach($featuredArticle as $article)
{
//trying to fetch article_category name from the nested data
{!! $article ->article_category ->name !!}
}
上面的代码在 laravel 7 中正确获取文章类别名称,但在 laravel 8 中加载文章类别名称失败。这是我收到的错误消息
ErrorException thrown with message "Trying to get property 'name' of non-object (View: /var/www/html/IkoNews/resources/views/site/index.blade.php)"
我希望它会显示
Politics
连同前面提到的其他数据。
【问题讨论】:
-
可能是 laravel 8 加载嵌套数据的问题,还是他们改变了我们从嵌套 JSON 中提取数据的方式??
标签: php laravel-blade laravel-8