Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hewaa's avatar
Level 1

How to count male or female for each country ?

Models

Country->region->city->Employ (Gender ) hasMany (Employ)

Employ have gender_id[1 - male, 2-female]) my qustion in (CountryIndex) how to count male or female for each country by id 1-male 2 -femal ?

public function getItem(){

    $countries = Country::query();

    // Search

    if (!empty($this->term)&& $this->term != null)
    {
        $countries = $countries->search(trim($this->term));
    }

    // * Trashed

    if ($this->trashed){
        $countries = $countries->onlyTrashed();
    }else{
        $countries = $countries->withCount('region');
        $countries = $countries->withCount('city');
        $countries = $countries->withCount('employ');
        Male  ?????
        Female  ????
    }

id Country City Emp male female

1 USA 33 2650 ? ?

0 likes
34 replies
Shivamyadav's avatar

Try this

    $countries = Cuntry::query();

    // Search

    if (!empty($this->term)&& $this->term != null)
    {
        $countries = $countries->search(trim($this->term));
    }

    // * Trashed

    if ($this->trashed){
        $countries = $countries->onlyTrashed();
    }else{
        $countries = $countries->withCount('city');
        $countries = $countries->withCount('employ');
        $countries = $countries->where('column name', 'Male')->count();
Like this second one do replace male with female
        Male  ?????
        Female  ????
    }
Shivamyadav's avatar

@hewaa share me your code ..and tell me the name of your coloumn in which your data ( male and female) are storing in your database.

Shivamyadav's avatar

@hewaa try this and share your screenshot to me on my email address

    $countries = Cuntry::query();

    // Search

    if (!empty($this->term)&& $this->term != null)
    {
        $countries = $countries->search(trim($this->term));
    }

    // * Trashed

    if ($this->trashed){
        $countries = $countries->onlyTrashed();
    }else{
        $countries = $countries->withCount('city');
        $countries = $countries->withCount('employ');
        $countries = $countries->where('gender_id', 1)->count(); //for male 
		$countries = $countries->where('gender_id', 2)->count(); //for female

    }

Shivamyadav's avatar

@hewaa have that you seen there it is showing that ...

select count() from generals where....

that means it is selecting the general table and searching that column gender_id in that table.

Shivamyadav's avatar

@hewaa okay has You then created any relation with the employ to the generals or your country table?

hewaa's avatar
Level 1

@Shivamyadav no just in model General said hasmany gender and on Gender belongto General but in migration table there is not have any relashionship

Shivamyadav's avatar

@hewaa but this will work for you ,just you have to set the foreign id and by using the relationship method you have to just simply call the the method in the conntroller..

    $countries = Cuntry::query();

    // Search

    if (!empty($this->term)&& $this->term != null)
    {
        $countries = $countries->search(trim($this->term));
    }

    // * Trashed

    if ($this->trashed){
        $countries = $countries->onlyTrashed();
    }else{
        $countries = $countries->withCount('city');
        $countries = $countries->withCount('employ');
        $countries = $countries->where('gender_id', 1)->count(); //for male 
		$countries = $countries->where('gender_id', 2)->count(); //for female
		//you have to just to do it like this.
   		$countries = $countries->your relationship method() here and everyting will be same->where('gender_id', 1)->count(); //for male 

    }


Shivamyadav's avatar

@hewaa From my knowledge there is no logic for fetching the data from one table to another table with using slug slug is used for route model binding...

hewaa's avatar
Level 1

@Shivamyadav $generals = $generals->with('employ')->where('gender_id', 1)->count();

but stall say Unknown column 'gender_id'

ok i send you

1 like
Shivamyadav's avatar

@hewaa now try this code

    $countries = Cuntry::query();

    // Search

    if (!empty($this->term)&& $this->term != null)
    {
        $countries = $countries->search(trim($this->term));
    }

    // * Trashed

    if ($this->trashed){
        $countries = $countries->onlyTrashed();
    }else{
        $countries = $countries->withCount('city');
        $countries = $countries->withCount('employ');
        $countries = $countries->police()->where('gender_id', 1)->count();
		$countries = $countries->police()->where('gender_id', 2)->count();

    }

1 like
Shivamyadav's avatar

@hewaa try this import it on the top of the controller use Illuminate\Database\Eloquent\Police;

    $countries = Cuntry::query();

    // Search

    if (!empty($this->term)&& $this->term != null)
    {
        $countries = $countries->search(trim($this->term));
    }

    // * Trashed

    if ($this->trashed){
        $countries = $countries->onlyTrashed();
    }else{
        $countries = $countries->withCount('city');
        $countries = $countries->withCount('employ');
        $countries = $countries->police()->where('gender_id', 1)->count();
		$countries = $countries->police()->where('gender_id', 2)->count();

    }


Shivamyadav's avatar

use this code , I have updated it now and don't forget to import the class on the top of the controller!

hewaa's avatar
Level 1

@shivamyadav

Call to undefined method Illuminate\Database\Eloquent\Builder::police()

but this use App\Models\Police; like is not using

public function getItem(){

    $generals = General::query();

    // * Search

    if (!empty($this->term)&& $this->term != null){
        $generals = $generals->search(trim($this->term));
    }
    // * Trashed
    if ($this->trashed){
        $generals = $generals->onlyTrashed();
    }else{
        $generals = $generals->withCount('user');
        $generals = $generals->withCount('directorate');
        $generals = $generals->withCount('department');
        $generals = $generals->withCount('police');
        $generals = $generals->police()->where('gender_id', 2)->count();

    }
Shivamyadav's avatar

@hewaa replace it use App\Models\Police; with this

use Illuminate\Database\Eloquent\Police;
jlrdw's avatar

I did not try to read through all of that, but just use the aggregate function count with a group by.

1 like
hewaa's avatar
Level 1

@jlrdw please how do that can you give me a solution

i have 3 model (department -hasMany->Employ-belongsTo->Gender) i want count male for each department Employ column (department_id , gender_id ) i tried this code not work ( $department = $department->employ()->where('gender_id', 2)->count();)

hewaa's avatar
Level 1

@jlrdw really i'm confused it's hard to understand just write the code i was change to my code

jlrdw's avatar

@hewaa I don't have your data, but something like this, here I use ownerid instead.

SELECT dc_pets.ownerid, dc_pets.sex,
COUNT(dc_pets.sex) AS  count_gender
FROM dc_pets
WHERE dc_pets.ownerid >= 1
GROUP BY dc_pets.ownerid, dc_pets.sex;

query result

ownerid	sex	 count_gender
1 	M 	11
1 	f 	2
2 	M 	12
2 	F 	1
3 	M 	1
3 	F 	1
4 	F 	1
4 	M 	3
5 	m 	1
5 	F 	4

So the owner with the id of 1 has 11 male pets and 2 female pets.

To get the exact format you need, just use a little trial and error.

Edit:

Also experiment with case and sum. A little trial and error is usually all it takes.

2 likes
rodrigo.pedra's avatar
Level 56
$countries = Country::query()
    ->when(trim($this->term ?? ''), fn ($query, $term) => $query->search($term))
    ->when(
        $this->trashed,
        fn ($query) => $query->onlyTrashed(),
        fn ($query) => $query->withCount([
            'region',
            'city',
            'employ',
            'employ as male_count' => fn ($related) => $related->where('gender_id', 1),
            'employ as female_count' => fn ($related) => $related->where('gender_id', 2),
        ]),
    )
    ->get();

References:

2 likes

Please or to participate in this conversation.