I am making a blog in Laravel Framework. I want to send posts to the frontend view that have a specific category. How can i do this when i have a separate category table that is connected to the posts table? For example, my posts table has a category_id that is connected to the category table.
Post model:
public function category(){
return $this->belongsTo('App\Category');
}
Category model:
public function posts(){
return $this->hasMany('App\Post');
}
Now, how can i send posts to the view, but only posts that have a specific category, for example "Archive"?
I know it should be something like:
public function index()
{
$rows = Post::notdeleted()->get();
return view('admin.posts.index', compact('rows'));
}
but i dont know how to get the category since it is a category_id 1 in posts table and "archive" in category table.
I think you want to filter the post by category name.
public function index(){
// For example Archive
$categoryName= request()->get('category_name');
$posts = Post::whereHas('category',function($query) use ($categoryName){
$query->where('name','like',"%{$categoryName}%");
});
return view('admin.posts.index', compact('posts'));
}
You can do something like this:
public function index()
{
$rows = Post::whereHas('category',function($q){
$q->where('category_name','archive');
})->get();
return view('admin.posts.index', compact('rows'));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.