You can use withCount method:
https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I currently have 3 tables. 1st is Organization table which stores the Organization details made by a certain User. User table is for users. 3rd is Favorite Organizations table which is when a user follows a organization the organization_id and user_id is added to favourite_organization table. I want to count the total number of times a organization_id has been stored on favourite_organization table and send it alongside the organization array. Here is what i have done upto now.
public function favouriteOrganizationList(){
//Grabbed the organization_id that are present as the logged in user.
$fav_org_list = DB::table('favourite_organizations')->where('user_id', Auth::id())->pluck('organization_id');
//Fetched the organization details based on the above ids.
$fav_organization_details = DB::table('organizations')->with('organizationFollowers')->whereIn('id', $fav_org_list)->get();
return $fav_organization_details;
}
If possible i want to send the count of the organization in the favourite_organization table inside the $fav_organization_details array.
@subit If you define the relationship on the User model you can simplify it:
Auth::user()->favoriteOrganizations()->withCount('organizationFollowers')->get();
That way you don't have to query the database twice.
Please or to participate in this conversation.