I have the following in my index function of my controller
public function index()
{
$posts = Blog::inRandomOrder()
->with(['tags'])
->limit(3)
->get(['post_title','post_context','post_slug']);
return view('welcome', [
'posts' => $posts,
'home' => true
]);
}
My Blog model has the following relationship set up
public function tags()
{
return $this->belongsToMany(Tags::class, 'tags_posts');
}
And my tags model has the following relationship set up
function blog()
{
return $this->belongsToMany(Blog::class, 'tags_posts');
}
And everything works in the show function of my controller
public function show($post_slug)
{
$blog = Blog::where('post_slug', $post_slug)->firstOrFail();
return view('blog.post', [
'post' => $blog,
'tags' => $blog->tags()->get(['tag_name']),
'extendPageTitle' => $blog->post_title,
'blog' => true
]);
}
In the blog/post-slug-1 the tags are displayed, but when I try to combine the tags with eloquent in my index function of my controller, the tags collection is added to the object, but it's empty, even though each post has 2 tags associated with it.
Than in my view I've put the following code inside the foreach loop
<pre>{{ print_r($post->tags) }}</pre>
And that is giving me the following for each blog post
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
)
[escapeWhenCastingToString:protected] =>
)
1