Laravel - How to use subquery in select statement?

Laravel - How to use subquery in select statement?

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);    

Phone: (+91) 8800417876
Noida, 201301
Attention Required! | Cloudflare

Sorry, you have been blocked

You are unable to access ressim.net

Why have I been blocked?

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.