Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to use distinct() with pagination() in laravel 5.2 with fluent and it's given result proper but pagination remain same(Like without apply distinct).

I have already reviewed and tested below answers with mine code
- laravel 5 - paginate total() of a query with distinct
- Paginate & Distinct
- Query Builder paginate method count number wrong when using distinct

My code is something like:

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

EXAMPLE
- I have result with three records(i.e. POST1, POST2, POST3 and POST1) so I apply distinct().
- Now my result is POST1, POST2 and POST3 but pagination still display like 4 records(As result before applied distinct()).

Any suggestion would be appreciated!

like image 482
AddWeb Solution Pvt Ltd Avatar asked Dec 22 '16 12:12

AddWeb Solution Pvt Ltd


People also ask

How can I use pagination in Laravel 8?

To perform pagination in laravel, you just have to use the paginate () function instead of all () or get() functions as used in maximum time. Paginate method takes a number as a parameter. It defines how much data you want to show on one page or section.

How can I get pagination count in Laravel?

To Get Current Page Total$paginator->count() Get the number of items for the current page.

How do I paginate an array in Laravel?

In this example, we will simple create one route and call controller method. that controller method we will create our custom array and convert into collection object. we also create one paginate() in same controller to create pagination in laravel. then you have to just call view and pass result variable.


1 Answers

Pass the colom name in distinct()

I have multiple tables joined and need distinct data. So listings work perfectly with distinct but the total records count during pagination was wrong and I landed on this thread. later, I was able to solve this by passing an argument in the distinct method.

DB::table('myTable1 AS T1')
    ->select('T1.*')
    ->join('myTable2 AS T2','T2.T1_id','=','T1.id')
    ->distinct(['T1.id'])
    ->paginate(5);
like image 118
Govind Totla Avatar answered Nov 15 '22 17:11

Govind Totla