Laravel Group By Using eloquent with example

laravel group by using eloquent

In this article, we will learn about the laravel group by and how to do it using eloquent, but before moving forward let’s see what is a group by in SQL.

SQL groupby statement

The GROUP BY statement groups rows that have the same values into summary rows, like “find the number of customers in each country”.

The GROUP BY the statement is often used with aggregate functions (COUNT()MAX()MIN()SUM()AVG()) to group the result-set by one or more columns.

If you want to learn more about the SQL group by statement you can learn from here and If want to go in-depth with laravel eloquent you can learn from here.

Now we will understood this grouby statement by using the below example.

Let’s Suppose I have table Named as customer’s table which have the below data, and we have to apply group by on the basis of the country.

IDCustomerNameContactNameAddressCityPostalCodeCountry
1
Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

We will write the below code to get the group based on the country.

$customerCount = Customer::groupBy('country')->select('country', DB::raw('count(*) as total'))->get();

If you don’t want to use laravel eloquent and you like to db table, then I thought the below command is beneficial and the below code is useful for you.

$customerCount= DB::table('customers')
                 ->select('country', DB::raw('count(*) as total'))
                 ->groupBy('country')
                 ->get();

Now I thought you have the basic idea of working with laravel group by if you believe I am able to resolve your problem then rate me 5.

5 1 vote
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x