So I’m making a blog website and I’m implementing tags. I keep getting the error in the title and not sure what I’m supposed to do. I’ve looked through similar questions here but they look different from how i’ve done it. Im using pivot tables for the the tags. When I did it with the posts only it worked well and displayed everything here is the index method from my posts controller.
public function index() { $posts = Post::all()->sortByDesc('created_at'); return view('blogs.blogs', compact('posts')); }
here is the index method from my tag controller.
public function index(Tag $tag){ $posts = $tag->posts(); return view('blogs.blogs')->with('posts',$posts); }
Here is how I’m outputting it in the view
@foreach($posts as $post) <div class="well row"> <div class="col-md-4"> <img style="width: 100%" src="/storage/cover_images/{{$post->cover_image}}" alt=""> </div> <div class="col-md-8"> <h3> <a href="/posts/{{$post->id}}">{{$post->title}}</a></h3> <h3>{{$post->created_at}}</h3> </div> </div> @endforeach
This is my tags model
public function posts() { return $this->belongsToMany(Post::class); } public function getRouteKeyName() { return 'name'; }
Advertisement
Answer
Error
Your error comes from the fact that the variable $post
within your foreach loop has returned as a non-object.
Probable Cause
That $posts
is not being returned as a collection but rather a query builder instance
$posts = $tag->posts();
If you have built an eloquent relationship between a Tag
model and a Post
model, when you access this as a method (i.e. $tag->posts()
) you will get an eloquent query builder instance. If you access this as a property (i.e. $tag->posts
), it will return an eloquent collection.
Suggestion
Try passing the posts to the view as a collection
public function index(Tag $tag) { return view('blogs.blogs', [ 'posts' => $tag->posts ]); }
And try using a @forelse
loop to catch the instances where you have no posts
@forelse ($posts as $post) @empty @endforelse