
Table of contents

In this post, you will learn how to implement Laravel eloquent group by the method. I will give you a simple example so that the Laravel eloquent groupBy() is easier for you to understand and implement in your Laravel project.
Laravel groupBy() will help you to query with the field as a group and return grouped data from your database table. It is supposed to be multiple records with the same type or value in your database.
We can get a specific type of data without duplicating the value using Laravel groupBy() method which is really helpful in reporting queries.
Example #1: Laravel Group By - Display Records By Field
The below query will display each timezone with users under the timezone.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::orderBy('created_at')->get()->groupBy(function($data) {
return $data->timezone;
});
foreach($users as $timezone => $userList) {
echo '<ul>';
echo '<li>' . $timezone . '</li>';
echo '<ul>';
foreach($userList as $user) {
echo '<li>User Email: ' . $user->email . '</li>';
}
echo '</ul>';
echo '</ul>';
}
}
}
Result:
NOTE: This is just an example kindly transfer the loop inside your blade file.
Example #2: Laravel Group By - Count By Field
This will display the total records under the group field.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use DB;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::select('timezone', DB::raw('count(*) as total'))
->groupBy('timezone')
->pluck('total','timezone')
->toArray();
print_r($users);die;
}
}
Output:
Array
(
[Asia/Manila] => 1
[UTC] => 2
)
Example #3: Laravel groupBy() - Count By Period
If you want to use the Laravel groupBy() method with periods like by DAY, WEEK, MONTH, YEAR the below code will help you.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::orderBy('created_at')->get()->groupBy(function($data) {
return \Carbon\Carbon::parse($data->created_at)->format('F');
})
->map(function($entries) {
return $entries->count();
})
->toArray();
print_r($users);die;
}
}
For DAY:
return \Carbon\Carbon::parse($data->created_at)->format('Y-m-d');
For WEEK:
return \Carbon\Carbon::parse($data->created_at)->format('W');
For MONTH:
return \Carbon\Carbon::parse($data->created_at)->format('F');
For YEAR:
return \Carbon\Carbon::parse($data->created_at)->format('Y');
Result:
Array
(
[May] => 2
[June] => 1
)
That's all for Laravel groupBy() method. I hope it helps thank you for dropping by :)

Read next
