Here u go.
Route::get(/category/{slug});
public function postCategory($slug)
{
$posts = Post::where('slug', $slug)->get();
return view('front.posts.category', compact('posts'));
}
Is this what you want?
I have two(2) tables;
Posts: id, title, slug, category_id, body, is_published, created_at, updated_at
Categories: id, name, slug, created_at, updated_at
And here's my Post & Category model;
Post:
public function category()
{
return $this->belongsTo(Category::class);
}
Category:
public function posts()
{
return $this->hasMany(Post::class);
}
And here's my controller to retrieve a posts by category. (But for now, I retrieve the category directly via category_id in posts table itself)
public function postCategory($id)
{
$posts = Post::where('category_id', $id)->get();
return view('front.posts.category', compact('posts'));
}
Finally my route;
Route::get('/category/{id}', 'PostController@postCategory')->name('post.category');
The question is, how can I use slug wildcard in categories table to replace the category_id I currently use.
I want my route to be like this:
Route::get(/category/{slug}); // http://example.com/category/laravel
I thought it's there cause your first post says so.
$posts = Category::where('slug', $slug)->first()->posts;
Can you try this?
Please or to participate in this conversation.