How to group by and count in laravel blade?

by dalton_moen , in category: PHP Frameworks , 5 months ago

How to group by and count in laravel blade?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 5 months ago

@dalton_moen 

To group by and count records in Laravel Blade, you can use the groupBy and count methods in your controller and then pass the results to the Blade view. Here's an example of how you can do this:


Controller code:

1
2
$data = Model::all()->groupBy('column_name')->map->count();
return view('your_blade_view', compact('data'));


Blade view code:

1
2
3
@foreach($data as $key => $count)
    <p>{{ $key }}: {{ $count }}</p>
@endforeach


In this example, Model is the name of your database model, column_name is the name of the column you want to group by, and your_blade_view is the name of your Blade view file. The controller code groups the records by a specified column and then counts the number of records in each group. The results are then passed to the Blade view using the compact function.


In the Blade view code, you can iterate over the grouped and counted data using a foreach loop and display the results as needed.