Group by in Laravel
Today, you will learn how to implement Laravel eloquent group by the method. I will give you a very simple example so that the Laravel eloquent groupBy() is easier to understand and implement in your Laravel project. In this tutorial, I will explain How to implement Group by Eloquent in Laravel. groupBy() will help you query the field as a group and return grouped data from your database table. groupBy() method a specific type of data without duplicating the value, which is really helpful in reporting queries.
Example 1: Laravel Group By-Display Records By Field
The below example will display each age with users under the age.
Example
<?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->age;
});
foreach($users as $age => $userList) {
echo '<ul>';
echo '<li>' . $age . '</li>';
echo '<ul>';
foreach($userList as $user) {
echo '<li>User Name: ' . $user->name . '</li>';
}
echo '</ul>';
echo '</ul>';
}
}
}
Output
Example 2: Laravel Group By – Count By Field
The below example will display the total records under the group field.
Example
<?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::select('age', DB::raw('count(*) as total'))
->groupBy('age')
->pluck('total','age')
->toArray();
echo '<pre>';
print_r($users);
}
}
Output
Array
(
[20] => 3
[21] => 2
[22] => 1
)
Example 3: Laravel Group By – Count By Period
The Laravel groupBy() method with periods like by DAY, WEEK, MONTH, and 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 = App\Models\User::orderBy('created_at')->get()->groupBy(function($data) {
// If you want get Month wise, then use the below example
return \Carbon\Carbon::parse($data->created_at)->format('F');
// If you want get DAY wise, then use the below example
// return \Carbon\Carbon::parse($data->created_at)->format('Y-m-d');
// If you want get Week wise, then use the below example
// return \Carbon\Carbon::parse($data->created_at)->format('W');
// If you want get Year wise, then use the below example
// return \Carbon\Carbon::parse($data->created_at)->format('Y');
})->map(function($entries) {
return $entries->count();
})->toArray();
echo '<pre>';
print_r($users);
}
}
Output
Array
(
[April] => 2
[May] => 3
[July] => 6
)