Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Pranam's avatar

Pagination with join table not working getting duplicate value with groupBy or unique() or distinct().

Pagination with multiple tables joined not working to get the unique value in the query and only working with get() method. I have also orderBy in the query. Unique value is not achieved and in the example below using unique with paginate i am getting 5 unique items and with get i am getting 9 unique items and while using groupby and distinct no unique selected values are found. It will be difficult if we have large data so how to achieve it.

//Code 1
//Working properly with get method
Model::join('table_A', 'table_B.id', '=', 'table_A.id')
                ->select([table_A.title', 'table_A.category_id', 'table_B.item', ])
                ->orderBy('table_A.created_at', 'desc')
	->unique('item')
    ->get();

//Code 2
//Not Working with paginate & ->groupBy //No unique with this query
Model::join('table_A', 'table_B.id', '=', 'table_A.id')
                ->select([table_A.title', 'table_A.category_id', 'table_B.item', ])
                ->orderBy('table_A.created_at', 'desc')
    ->groupBy('table_B.item')
    ->paginate();

//Code 3
 // Not Working with paginate & ->distinct //No unique with this query
Model::join('table_A', 'table_B.id', '=', 'table_A.id')
                ->select([table_A.title', 'table_A.category_id', 'table_B.item', ])
                ->orderBy('table_A.created_at', 'desc')
	->distinct('item')
    ->paginate();

//Code 4
// Not Working properly with paginate & ->unique. In this example i am getting 9 unique value when using get() and when using paginate 5 unique value are achived.
Model::join('table_A', 'table_B.id', '=', 'table_A.id')
                ->select([table_A.title', 'table_A.category_id', 'table_B.item', ])
                ->orderBy('table_A.created_at', 'desc')
	->unique('item')
    ->paginate();
0 likes
2 replies
Sinnbeck's avatar

Please explain how it isnt working. It takes out the guess work

Pranam's avatar

@Sinnbeck Sir actually I am getting the values but I am not getting the unique values and with paginate, I am getting mostly duplicate values. In get() method I am able to get the unique values but while using paginate with groupBy or unique() or distinct(), I am mostly getting duplicate values. with default laravel page size of paginate is 15 and most of them are duplicate values and while using get() method, I am getting 9 unique values. If we have a large data set then this would be a problem and so I have put up this question. Sir how to achieve this, if possible please help me.

Please or to participate in this conversation.