Laravel Select with Count Query with Group By Example

By Hardik Savani November 5, 2023 Category : Laravel

Hi,

In this profound tutorial, we will learn laravel select count group by. I would like to share with you laravel select count group by. let’s discuss about laravel raw query count. we will help you to give an example of laravel query count rows. Let's get started with laravel count records.

We always required to get count of number of records or number of inserted record of current month etc in laravel. We can use mysql count function in laravel eloquent. We have two way to get count of column value. first we can use laravel count() of query builder and another one we can use with directly with select statement using DB::raw(). I give you both example you can see and use any one as perfect for you.

Example:

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Click;

use DB;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$data = Click::select("id", DB::raw("COUNT(*) as count_row"))

->orderBy("created_at")

->groupBy(DB::raw("year(created_at)"))

->get();

dd($data);

}

}

I hope it can help you...

Tags :
Shares