php - How to simplify a SQL "IN" loop query from 1 to multiple IN checks in the same query?

I'm trying to simplify this part of code where I call a loop DB query to a single DB query that i run a loop over the results afterwards.
My question now is how can I not only get the apps count of one category where a row in the app_categories table exists but the result of every categories count at once?
Current code:
foreach(DB::Table('categories')->get() as $category)
{
$appcount[$category->name] = DB::Table('apps')->where('active', 1)
->whereRaw('apps.id in (select app_id from app_categories where category_id = ?)', [$category->id])
->count();
}
Answer
Solution:
this will suit your need.
DB::table('categories')
->select('categories.id as category_id','categories.name as name',DB::raw('count(*) as apps_count'))
->leftJoin('app_categories','categories.id','=','apps_categories.category_id')
->leftJoin('apps','apps.id','=','apps_categories.app_id')
->where('apps.active',1)
->groupBy('categories.id')
another solution is using eloquent relation
https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: invalid argument supplied for foreach() laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.