Laravel – How to use subquery in select statement?

Laravel – How to use subquery in select statement?

In this post we will give you information about Laravel – How to use subquery in select statement?. Hear we will give you detail about Laravel – How to use subquery in select statement?And how to use it also give you demo for it if it is necessary.

In this tutorial, I will let you know how to write subquery inside the select statement in Laravel 5.
Laravel allows users to write a raw query using DB::raw() method.


Use Case

Sometime we need to develop the application where we need to get user details with their followers like “Instagram” app.

In Instagram app when you visit the user profile, you will see the total number of posts, their followers and following count.

In this scenario, we can write a mysql function or use subquery in select statement.

For this example, i will have two tables users and user_followers.

Let’s assume that user table has fields id, name, email and user_followers table has id, user_id, follower_id.

First i will use the MySQL raw query to get details in following way :


MySQL Raw Query

SELECT 
 users.*, 
 (SELECT count(*) FROM user_followers
   WHERE user_followers.user_id = users.id
  ) as total_followers
FROM 'users'


Laravel Query Builder

Now I will write the query in Laravel to achieve same functionality.

  $data = DB::table("users")
          ->select("users.*",
                  DB::raw("(SELECT count(*) FROM user_followers
                          WHERE user_followers.user_id = users.id
                        ) as total_followers"))
          ->get();
  dd($data);    

You can write the subquery with join statement.

Hope this code and post will helped you for implement Laravel – How to use subquery in select statement?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  49  =  59

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US