Laravel-9 Tutorial – Laravel 9 Group By Example: groupBy() Value in Laravel

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(AppStudent::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$3z#21$TKh4H2.PfRx12YgZzwiaB.KjNyAxaxb9cbcoZgdIVFlYg8B65adAm', 
        '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(AppStudent::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 AppHttpControllers;
use IlluminateHttpRequest;
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)
        <tr>
            <th colspan="3"><strong>{{ $day }}: {{ $students_list->count() }} students<strong></th>
        </tr>
        @foreach ($students_list as $student)
            <tr>
                <td>{{ $student->name }}</td>
                <td>{{ $student->email }}</td>
                <td>{{ $student->created_at }}</td>
            </tr>
        @endforeach
    @endforeach
</table>

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.

Leave a Reply

Your email address will not be published. Required fields are marked *