Laravel 7|8 Group By Example: groupBy() Value in Laravel

Last updated on by Digamber

While working with data we require to handle it through various methods. Today we are going to learn how to create a collection of data using Laravel groupBy method.

The groupBy() 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.

I assume you have already set up the app, and we require to generate some fake data to sustain the consistency of records for this tutorial.

Let’s seed 100 fake users by defining the date for particular events.

You can keep the following data in the database/factories/StudentFactory.php file:

$factory->define(App\Student::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$3z#21$TKh4H2.PfRx12YgZzwiaB.KjNyAxaxb9cbcoZgdIVFlYg8B65adAm', // secret
        'remember_token' => str_random(10),
        'created_at' => now()->subDays(rand(1,40)),

We are going to seed 100 students’ records, here is the final configuration of database/seeds/DatabaseSeeder.php file.

class DatabaseSeeder extends Seeder
    public function run()
        factory(\App\Student::class, 100)->create();

Laravel Group By Data Example

Now, here we get the answer about how to group the data in laravel. Just create the controller app/Http/Controllers/StudentController.php and add the following code in it.

The “Group By” function belongs to the Collection, not Eloquent category. So, always use get() method before groupBy() otherwise it won’t work as expected.


namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Student;

class StudentController extends Controller
    public function index(Request $request)
        $students = Student::orderBy('created_at')->get()->groupBy(function($data) {
            return $data->created_at->format('Y-m-d');

        return view('home', compact('students'));


Display Group By Data in View

Create a resources/views/home.blade.php file and insert the given below code:

<table class="table">
    @foreach ($students as $day => $students_list)
            <th colspan="3"><strong>{{ $day }}: {{ $students_list->count() }} students<strong></th>
        @foreach ($students_list as $student)
                <td>{{ $student->name }}</td>
                <td>{{ $student->email }}</td>
                <td>{{ $student->created_at }}</td>

Now, we have looked through students list and displayed the data using groupBy() method that is extremely easy and can be groupBy with the callback function.