Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

srikanthgopi's avatar

Lists posts from a single category

Let's say there are three categories 1.Fruits 2.Books 3.Clothes.

And a table called posts

On my site.com/books i want to show all the posts that belong to category 1(that is books)

Here is the route Route::get('/posts/books', 'PostsController@books'

I have the current code in my PostController Books Method

public function books(){$posts=Post::latest()->paginate('10); return view('posts.books', compact('posts'));}

How to fetch records only from books category. Im learning laravel and would like to know how to fetch records from a single category with where statement

0 likes
2 replies
burlresearch's avatar
Level 40

You're going to do this a lot, so make sure you read the docs:

https://laravel.com/docs/5.5/eloquent-relationships#querying-relations

Here you know you want only the book-type Posts, since that is explicit in your route, so in your controller:

$bookPosts = Post::where('category', 'books')->get()

Of course, you could make this more general by using a route parameter:

Route::get('posts/{category}', function ($category) {
    return Post::where('category', $category)->get();
});
1 like
srikanthgopi's avatar

Thanks @burlresearch I understood now. Thanks its working. I saved category id and i was using where('category_id', '2'). I changed it to where('category_id, '2') and it worked.

Im used yii2 framework earlier so was used to where(category_id=2) code so getting confused. I guess ill read the whole documentation again.

Please or to participate in this conversation.