The groupBy() method in Laravel returns the query results by grouping the data of a database table. Suppose we have multiple data of the same type or name in our database.

We can get those specific types of data without any duplicate value by using the groupBy() method. In this tutorial, you are going to learn how to use the groupBy() method in Laravel with examples.

Let’s assume, we have a database table named salaries where we can store the salary of teachers department-wise. There can be multiple departments in the database like this-

 groupBy() method in Laravel

Now, if we want to know, how many departments are available in the salaries table, we can use the groupBy() method to find out. It takes column name as an argument. The example is given below-


public function view(){

    $departments = Salary::select('department')
    return view('view_department', compact('departments'));        

From the Salary model, we can select the column name, in our case that is the department, and perform the groupBy() operation to get all the department’s names without any duplication of the data.

After retrieving the department data we can simply pass the data through the compact() function to view in the HTML file.

HTML view:

<div class="container">
  <h1>Available Departments</h1><hr>

  @foreach ($departments as $data)
      <p><b> {{$data->department}} </b></p>

We can perform a foreach loop with the retrieved data to show the department names.


 groupBy() method in Laravel

Here, you can see all the departments’ names, and they are not repeated. Though we have multiple duplicate entities in our database with multiple teachers from the same department. So, that’s how you can use the groupBy() method in Laravel. Thank you.