How To Use Group By Statement With Example Using Laravel

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems. The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

How to Use Group By statement in Laravel

 Syntax SQL GROUP BY Statement.

​SELECT column_name list
FROM table_name
WHERE condition
GROUP BY column_name list
ORDER BY column_name list;

The GROUP BY statement  used for functions ( MAX, MIN,COUNT, SUM, AVG) to group the result-set by one or more columns.
The GROUP BY statement  used for JOINS.
To learn more about SQL, please visit our BajarangiSoft site.



How can you use Group By statement in laravel
The groupBy  methods may be used to group the query results. 

Example(1)

​​<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;//include this

class UserController extends Controller
{
    public function index()
    {
        $user = DB::table('user')
        ->select('gender', DB::raw('count(*) as different_gender'))
        ->groupBy('gender')
        ->get();
        return view('user.index', ['users' => $users]);
    }
}
?>

the above example group the gender and count the number of gender and that fetch as different_gender that return from controller to user index.blade.php page.

Related Post