Laravel Group By Using eloquent with example

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.

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
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'))

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.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

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

Back to top button