У меня есть сводная таблица post_tag
между таблицами сообщений и тегов.
Я хочу показать теги, принадлежащие посту, в API ресурса?
Фрагменты кода файла ресурса:
public function toArray($request)
{
return [
'Name'=> $this->title,
'Descrption'=> $this->desc,
'Image'=> $this->image,
'Posted By'=> $this->user->name,
'Category Name'=> $this->category->name,
'Tags' => $this->whenPivotLoaded('post_tag', function () {
return $this->tags->name;
}),
];
}
Отношение добавлено в модель сообщения:
public function tags()
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
Файл PostController. php:
public function index()
{
$posts = PostResource::collection(Post::get());
return $this->apiRespone($posts , 'All Post', null ,200);
}
Один из результатов API:
{
"Name": "first post",
"Descrption": "desc of the post",
"Image": "SjvDfC1Zk5UzGO6ViRbjUQTMocwCh0lzEYW1Gufp.jpeg",
"User Name": "test",
"Category Name": "web dev"
},