the livewire component is route bonded as:
Route::get('/post/{post}', Bycategory::class)->name('posts.by-category');
in-home view I want to click on the category name and get all posts with same category:
@foreach($post->categories as $category)
<a href="{{ route('posts.by-category', $category) }}">{{ $category->name }}</a>
@endforeach
this is bycategory livewire class:
public Post $post;
public function render()
{
Post::with('categories')->where(function ($q){
$q->where('category_id', $this->post->categories()->id);
})->get());
return view('livewire.post.bycategory', compact('posts'))->layout('layouts.app');
}
the post and categories have many to many relations with the category_post table
but I get an error that there is not category_id in Post model;
the $this->post->categories()->id show the category id of that post;
As you mentioned that the the error above, it is clear that posts table
does not have the category_id column
and that is why you get this error. I think this is the right way to do this query
Post::with('categories' , function ($query) { $query->where('categories.id', $this->post->categories()->id);} )->get());