How to select from subquery using Laravel Query Builder?

Today, We want to share with you How to select from subquery using Laravel Query Builder?.In this post we will show you Laravel 5.8 How to Select from Sub-query using Laravel Query Builder, hear for How to select from subquery using Laravel Query Builder we will give you demo and example for implement.In this post, we will learn about Laravel – How to use subquery in select statement with an example.

How to select from subquery using Laravel Query Builder?

There are the Following The simple About How to select from subquery using Laravel Query Builder? Full Information With Example and source code.

As I will cover this Post with live Working example to develop Subquery in Laravel 5.8 ELOQUENT or Query Builder, so the select statement inside another select for this example is following below.

Example 1: laravel 5.8 subquery

$sub_query = Firstmodel::where(..)->groupBy(..); // Eloquent Builder instance

$data_count = DB::table( DB::raw("({$sub_query->toSql()}) as sub") )
	->mergeBindings($sub_query->getQuery()) // you need to get underlying Query Builder
	->count();
print_r($data_count);

$count_all_data = DB::table( DB::raw("({$sub_query->toSql()}) as sub") )
->mergeBindings($sub_query->getQuery())
->count();
print_r($count_all_data);

Example 2: laravel eloquent subquery

Laravel query

DB::query()->fromSub(function ($query) {
	$query->from('products')->groupBy('first_col1');
}, 'cat')->count();

MySQL Query

select count(*) as aggregate from (select * from `products` group by `first_col1`) as `cat`

Laravel - How to make subquery in select statement?

$data = DB::table("items")
  ->select("items.*",
			DB::raw("(SELECT SUM(items_stock.stock) FROM items_stock
						WHERE items_stock.item_id = items.id
						GROUP BY items_stock.item_id) as item_stock"),
			DB::raw("(SELECT SUM(items_sell.sell) FROM items_sell
						WHERE items_sell.item_id = items.id
						GROUP BY items_sell.item_id) as item_sell"))
  ->get();
Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about How to select from subquery using Laravel Query Builder?.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment