我正在 Laravel 8 上运行一个项目,并试图急切加载一些数据。数据按预期获取,但当我尝试将数据显示到我的刀片时出现问题。
我的控制器
public function siteHome(){
$featuredArticle = Article::with('articleCategory')->first();
return view('site.index', compact('featuredArticle'));
}
正确获取的 siteHome() 方法的响应
{
"id": 1,
"title": "politics",
"author": "nixon",
"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
以及前面提到的其他数据。