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