I was just wondering if there's a way in laravel to return a count on how many times a record exists with eloquent?
I have two tables: cars and brands.
Cars has de fields: id
, brand_id
. Brands has de fields: id
, name
. Relationship lies on cars.brand_id = brands.id
.
I have red the documents and couldn't find a solution.
Is there a way that I can how many times a brand is used by a car, so that i get the count like this:
Suzuki: 2<br>
Opel: 4 <br>
BMW: 1<br>
etc.
You could try a query:
SELECT count(brands.name), brands.name
FROM cars
JOIN brands ON cats.brand_id = brands.id
Use the equivalent for Eloquent
DB::table('cars')
->select(DB::raw('COUNT(brands.name), brands.name')
->join('brands', 'brands.id', '=', 'cars.id')
->groupBy('brands.name')
->get();
You should create a BelongsToMany relationship and then do a count in the query.
class Brand {
public function cars() {
return $this->belongsToMany('App\Car', 'brand_id', 'id');
}
}
Then use it like this:
Brand::where('name', 'Suzuki')->cars->count();
The nicest way to do this inside of your Brand model is with Aggregates:
If you have proper models you can do this:
$brands = Brands::with(cars)->get();
foreach ( $brands as $brand){
$yourarray[$brand->name]= count($brand->cars);
}
dd($yourarray);
This will give you a nice array with your brand and number of cars