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
sakarya escort sakarya escort bayan sakarya escort serdivan escort sakarya escort sakarya escort serdivan escort
karasu escort akyazı escort serdivan escort akyazı escort ferizli escort sapanca escort serdivan escort söğütlü escort sakarya escort izmit escort arifiye escort erenler escort hendek escort kocaali escort pamukova escort taraklı escort geyve escort