distinct() with pagination() in laravel 5.2 not working distinct() with pagination() in laravel 5.2 not working laravel laravel

distinct() with pagination() in laravel 5.2 not working


There seems to be some ongoing issues with Laravel and using distinct with pagination.

In this case, when pagination is determining the total number of records, it is ignoring the fields you have specified in your select() clause. Since it ignores your columns, the distinct functionality is ignored as well. So, the count query becomes select count(*) as aggregate from ...

To resolve the issue, you need to tell the paginate function about your columns. Pass your array of columns to select as the second parameter, and it will take them into account for the total count. So, if you do:

/*DB::stuff*/->paginate(5, ['T1.*']);

This will run the count query of:

select count(distinct T1.*) as aggregate from

So, your query should look like:

DB::table('myTable1 AS T1')    ->select('T1.*')    ->join('myTable2 AS T2','T2.T1_id','=','T1.id')    ->distinct()    ->paginate(5, ['T1.*']);


If it is possible, you can change distinct() with groupBy().


Use groupBy() instead of distinct(). I haven't tested but it will work. I was facing same issue in my query.

$author = Author::select('author_name')->groupBy('author_name')->paginate(15);