问题描述
我想在帖子视图中显示category_title。我正在对category_id和post_id使用透视图
发布模型:
public function categories()
{
return $this->belongsToMany(Category::class,'category_post','post_id','category_id');
}
Show.blade.php
{{$post->categories->category_title}}
但是告诉我这个错误
此集合实例上不存在属性[category_title]。
解决方法
您无法直接访问它,使用belongsToMany
您将获得多个对象。
要访问此文件,您需要按照以下说明进行操作。
@foreach($post->categories as $category)
{{ $category->category_title }}
@endforeach
或者您可以按以下方式访问它。
{{ $post->categories->pluck('category_title ')->implode(',') }}