Using aggregates functions in laravel

Sometimes, you will need to use the aggregates functions. No problem! Here is how you can do it with Eloquent.

  AppBook::count();

This is an example of its practical use:

  Route::get('book_get_books_count', function(){

      $booksCount = AppBook::count();
      return $booksCount;

  });

Exactly as you saw before for get() and first() methods, you can use aggregate methods with where methods. Here, we are counting the number of the books with more than 140 pages.

  Route::get('book_get_books_count', function(){

      $booksCount = AppBook::where('pages_count', '>', 140)->count();
      return $booksCount;

  });

Obviously, count() is not the only aggregate. Let’s see them with some other where() examples to do more practice. This time, we are searching for the minimum number of pages (but the books with more than 120 pages, at least).

  Route::get('book_get_books_min_pages_count', function(){

      $minPagesCount = AppBook::where('pages_count', '>', 120)->min('pages_count');
      return $minPagesCount;

  });

You can also do the same thing with max():

  Route::get('book_get_books_max_pages_count', function(){

      $maxPagesCount = AppBook::where('pages_count', '>', 180)->max('pages_count');
      return $maxPagesCount;

  });

Now, let’s find the average price for all the books that have the Book word in the name:

  Route::get('book_get_books_avg_price', function(){

    $avgPrice = AppBook::where('title', 'LIKE', '%Book%')->avg('price');
      return $avgPrice;

  });

Finally, let’s get the sum of all the page counts for all the books with more than 100 pages.

  Route::get('book_get_books_avg_price', function(){

    $countTotal = AppBook::where('pages_count', '>', 100)->avg('price');
      return $countTotal;

  });

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares