Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Laravel 8 using group by in view/blade by foreach

How to use groupBy on Foreach in Blade file in Laravel?

In this tutorial, I will give you an example of “How to use groupBy on Foreach in Blade file in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9 application.

First, what we’re doing here, This is the example :

groupBy example in foreach loop in blade file in laravel
groupBy in blade file in laravel 8

GroupBy Example in Laravel

The groupBy() a function is popularly known for grouping the query results in Laravel. It can allow us to group the data by particular event’s date, user registration date, and many more.

While working with data we require to handle it through various methods using GroupBy in the controller in the blade file. Today we are going to learn how to create a collection of data using the Laravel groupBy method in the Blade file in foreach loop in Laravel.

Student Table in Database:-

Group By example in blade file in foreach loop in Laravel

Route:-

Route::get('/list-student', [ComponentExampleController::class, 'listStudent']);

Controller:-

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller
{

    public function listStudent()
    {
        $cities = Student::select('city')->get();
        return view('studentlist',compact('cities'));
    }
}

Blade File:-

@foreach($cities->groupby('city') as $keys => $value)
                        
<h1>{{ $keys }}</h1>
           
@endforeach 

Run Application :

http://127.0.0.1:8000/list-student
Laravel 9 Group By in Blade file Example  in Laravel

In this article, we learned “Laravel 8 using group by in view/blade by foreach”, I hope this article will help you with your Laravel application Project.

Also Read:- Laravel Blade components.