Home > Software engineering >  Laravel: query a model with count?
Laravel: query a model with count?

Time:03-01

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

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

CodePudding user response:

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);
  • Related