It seems like you're encountering an issue with Laravel's paginator when using distinct() in combination with paginate(). The distinct() method is not being applied as you might expect when fetching the actual results, which is why you're seeing duplicate rows.
To resolve this issue, you can use a subquery to first select the distinct topics.id values and then join this subquery with the rest of your tables. This way, you ensure that the pagination is applied to a result set that already has distinct topics.id values.
Here's an example of how you can modify your query:
// First, create a subquery to select distinct topic IDs
$distinctTopics = Topic::select('topics.id')
->distinct()
->leftJoin('speakers', 'topics.speaker_id', '=', 'speakers.id')
->leftJoin('region_speaker', 'region_speaker.speaker_id', '=', 'speakers.id')
->whereIn('region_id', [6, 29, 30, 31, 32, 33, 34])
->where('category_id', '1')
->where('fee_id', '1')
->where('status', 'P')
->whereNull('topics.deleted_at');
// Then, use the subquery to join with the topics table and paginate the results
$topics = Topic::joinSub($distinctTopics, 'distinct_topics', function ($join) {
$join->on('topics.id', '=', 'distinct_topics.id');
})
->leftJoin('speakers', 'topics.speaker_id', '=', 'speakers.id')
->leftJoin('region_speaker', 'region_speaker.speaker_id', '=', 'speakers.id')
->select('topics.*', 'region_id') // Select the columns you need
->orderBy('subject', 'asc')
->paginate(15);
return view('your_view', compact('topics'));
In this solution, $distinctTopics is a subquery that selects the distinct topics.id values based on your conditions. Then, we use joinSub() to join this subquery with the topics table, ensuring that we only get distinct topics. Finally, we apply paginate() to the joined query.
This should give you the correct pagination without duplicate rows. Remember to replace 'your_view' with the actual view name you are using to display the results.