Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total number of records with Laravel?

MySQL has a feature for getting the total number of records a query would return without a limit, SQL_CALC_FOUND_ROWS. Does Laravel support this?

Currently I have to do it in two queries:

public function dataTable() {
    $bookings = DB::table('bookings')
        ->limit(Input::query('iDisplayLength'))
        ->offset(Input::query('iDisplayStart'))
        ->get();
    $count = $bookings = DB::table('bookings')
        ->count();
    return Response::json([
        'iTotalRecords' => $count,
    ]);
}

Not only will this be less efficient, but there's going to be a lot of redundant code once I add in all the ->where() criteria.

like image 522
mpen Avatar asked Mar 30 '14 18:03

mpen


2 Answers

For any complicated or vendor-specific queries, you generally have to pass the query directly with DB::raw(), e.g.:

$bookings = DB::table('bookings')
    ->select(DB::raw('SQL_CALC_ROWS_FOUND ...
like image 73
giaour Avatar answered Oct 13 '22 09:10

giaour


Refined what @giaour said.

$bookings = DB::table('bookings')
            ->select(array(DB::raw('SQL_CALC_FOUND_ROWS booking_id,name')))
            ->where('...')
            ->orWhere('...')
            ->take(10)
            ->skip(50)
            ->get();

$bookingsCount  = DB::select( DB::raw("SELECT FOUND_ROWS() AS Totalcount;") );

After SQL_CALC_FOUND_ROWS you can fetch count by SQL_CALC_FOUND_ROWS();

like image 25
kamlesh.bar Avatar answered Oct 13 '22 09:10

kamlesh.bar