Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel: query a model with count?

how can query in laravel with model method ?
i have a counter method in city model and i want to use this in my select query in response

how can i write this ?

my City model

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public function mobile()
{
    return $this->hasMany(Mobile::class);
}

public function mobile_count()
{
    return $this->mobile()->count();
}

my query

public function findCityWithID($id)
{
    $subgroup = City::select('id', 'name', 'state_id')->where('state_id', $id)->orderBy('name')->get();
    return response()->json($subgroup);
}

i want have in $subgroup each City mobile counts

>Solution :

The Model:

public function mobiles()
{
    return $this->hasMany(Mobile::class);
}

The Query:

$cities = City::withCount('mobiles')->where('state_id', $id)->get();

$response[];
foreach ($cities as $city) {
    response[
      'id' => $city->id;
      'name' => $city->state;
      'state_id' => $city->state_id;
      'mobile_count' => $city->mobile_count;
    ];
}

return response()->json($response);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading