#database #development #eloquent #laravel #php

We some times need to make queries to retrieve different kinds of rows from the same table.

1$published_posts = Post::where('status','=','published')->get();
2$featured_posts = Post::where('status','=','featured')->get();
3$scheduled_posts = Post::where('status','=','scheduled')->get();

The above code is retrieving rows with a different status from the same table. The code will result in making following queries.

1select * from posts where status = 'published'
2select * from posts where status = 'featured'
3select * from posts where status = 'scheduled'

As you can see, it is making 3 different queries to the same table to retrieve the records. We can refactor this code to make only one database query.

1$posts =  Post::whereIn('status',['published', 'featured', 'scheduled'])->get();
2$published_posts = $posts->where('status','=','published');
3$featured_posts = $posts->where('status','=','featured');
4$scheduled_posts = $posts->where('status','=','scheduled');
1select * from posts where status in ( 'published', 'featured', 'scheduled' )

The above code is making one query to retrieve all the posts which has any of the specified status and creating separate collections for each status by filtering the returned posts by their status. So we will still have three different variables with their status and will be making only one query.