Home > database >  Laravel: Multiple count for different tables
Laravel: Multiple count for different tables

Time:01-13

I have three different eloquent query for get count of my tables.

$posts = Post::where('published', true)->count();
$pages = Pages::where('published', true)->count();
$products = Product::where('published', true)->count();

There is a way for have an unique Eloquent query? (If is possible, I'd like don't use DB::raw).

Thanks!

CodePudding user response:

Write your code like in single query.

$data = DB::select("SELECT (SELECT COUNT(*) FROM posts WHERE published = true) as post_count, (SELECT COUNT(*) FROM pages WHERE published = true) as page_count, (SELECT COUNT(*) FROM products WHERE published = true) as product_count");

After that you can get record like

$data->post_count
$data->page_count
$data->product_count
  •  Tags:  
  • Related