ahmedesa/laravel-api-tool-kit

When using HasManyThrough and dynamicPaginate - wrong (duplicate) records are returned

Closed this issue · 3 comments

Describe the bug
If you take the laravel docs example https://laravel.com/docs/11.x/eloquent-relationships#has-many-through
and do
$project->deployments()->useFilters()->dynamicPaginate();

Then all the results will show only the first deployment. The count is correct.
If I change it to
$project->deployments()->useFilters()->get();
then then it works correctly.

I've also tested and it works correctly for a different hasMany relation.

So I tried to find a fix and I found that if I change

$results = ($total = $this->toBase()->getCountForPagination())
                ? $this->forPage($page, $perPage)->get(['*'])
                : $this->model->newCollection();

to

$results = ($total = $this->toBase()->getCountForPagination())
                ? $this->model->forPage($page, $perPage)->get(['*'])
                : $this->model->newCollection();

in MacroServiceProvider.php then issue is fixed, but it brakes the hasMany relation. It starts to show all rows instead of the related, but counts them correctly.

To Reproduce
replicate
https://laravel.com/docs/11.x/eloquent-relationships#has-many-through
and do
$project->deployments()->useFilters()->dynamicPaginate();

Expected behavior
To show expected records

does it work with normal build-in pagination?

yes it works as expected

After carefully reviewing the functionality and writing unit tests, I couldn't replicate any issues with dynamic pagination. The tests I've created simulate various scenarios, and the pagination appears to be working as expected.

Furthermore, I've examined the pagination implementation in Laravel's source code. It appears that the dynamic pagination logic we're using is same as the the pagination mechanism utilized by Laravel. Specifically, the code snippet you provided:

$results = $total
    ? $this->forPage($page, $perPage)->get($columns)
    : $this->model->newCollection();

This snippet indeed reflects the same logic used in Laravel's pagination mechanism. Therefore, I believe that the dynamic pagination functionality within our package is consistent with Laravel's standard behavior.

If you encounter any specific issues or discrepancies in the dynamic pagination functionality, please provide more details or examples so that we can further investigate and address them.