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

yaddly's avatar

Pagination adding route-parameter to page-links after Model update

Good day Laracons, I am using Route::resources([]) to generate routes, but I realized that I needed the page number from the url query string sent to controller action methods. So, I appended it to the route as query string:

href="{{ route('nationalities.edit', ['nationality' => $nationality?->id, 'page' => Request::query('page', 1)]) }}"

So, the url for edit action method is: http://127.0.0.1:8000/nationalities/19/edit?page=2

However, after updating/editing a record using the route above, I noticed that all paginated links now show http://127.0.0.1:8000/nationalities/19?page=2 - they're all pointing to the url above, which messes up the links.

Thank you for taking precious time out of your busy schedule to read through this question and for looking into the feasibility to solve this puzzle.

Update: The problem is coming from the observer, without the observer, the code works fine. I need the observer to clear and update cache when the model is updated.

Repository Class

class NationalityRepository implements NationalityContract
{
    use DataHelper, CacheHelper;

    const INDEX_CACHE_KEY = 'nationalities';

    const OPTIONS_CACHE_KEY = 'nationalityDropdownOptions';

    public function getModels(): mixed
    {
        $models = new Collection;

        try {

            $currentPage = $this->getCurrentModelPage();

            $models = Cache::rememberForever(self::INDEX_CACHE_KEY . "-page-$currentPage", function () {

                $model = resolve(Nationality::class);

                return $model?->orderBy('nationality', 'ASC')
                    ?->paginate($model?->getPerPage(), [
                        'id',
                        'nationality'
                    ])->withQueryString();
            });
        } catch (\Throwable $th) {

            LogServiceEvent::dispatch(LogLevel::Critical, __CLASS__, __FUNCTION__, $th?->getMessage(), $th?- 
            >getTrace());

            throw $th;
        }

        return $models;
    }
}
0 likes
15 replies
Tray2's avatar

The route doesn't care about those, so you don't need to add anything in your routes file.

yaddly's avatar

@Tray2 Thank you, but then I wonder what is causing the paginated links to change after an update.

yaddly's avatar

@Tray2 Hi, thank you for your pointers, after hours of troubleshooting this, I'm nowhere close to finding a working solution. However, I narrowed down the problem to my Observer event. If I comment out the observer attribute on the Model, the problem does not occur, but this results in my cache not getting cleared and updated with new data. I was wondering if you're in a position to assist with reviewing the observer code and the repository class that I suspect are not playing nicely together.

yaddly's avatar

I could not find the source of the error reported above. Anyhow, below is the ugly solution I could concoct after struggling for days on end without finding the source of the bug.

private function removeRouteParameter(LengthAwarePaginator $paginatedModels): LengthAwarePaginator
    {
        try {

            $paginatedModels = tap($paginatedModels, function ($paginator) {

                $routeParam = Str::of($paginator?->path())?->afterLast('/')?->__toString();

                if ($routeParam ?? false and is_numeric($routeParam)) {

                    $newPath = Str::remove(search: "/$routeParam", subject: $paginator?->path());

                    $paginator?->setPath($newPath);
                }

                return $paginator;
            });
        } catch (\Throwable $th) {

            throw $th;
        }

        return $paginatedModels;
    }
gych's avatar
gych
Best Answer
Level 29

Have you tried to use setPath already?

      return $model?->orderBy('nationality', 'ASC')
            ?->paginate($model?->getPerPage(), [
                'id',
                'nationality'
            ])->setPath(url('/nationalities'))->withQueryString();
yaddly's avatar

@gych Hi, yes, I have tried it out and it worked fine. I just realized that I over-engineered my version of your suggestion. I wrote a function that taps into the paginated result instead of just chaining the setPath('path') method.

yaddly's avatar

@gych Are you comfortable in helping me hunt down the bug causing this issue? I could privately share the git repo link?

gych's avatar

@yaddly Which issue are you still having right now after using setPath?

yaddly's avatar

@gych There's no issue at all after using setPath() method but I am still wondering what caused this bug that had to be fixed using setPath().

gych's avatar

@yaddly Ok that's good, to me it seems like the issue you're having might be caused by how you use the resource router.

Can you share the code of your resource route for nationalities?

yaddly's avatar

@gych Thank you 😊 very much, it's almost midnight in South Africa, will share the git repo later. I take it that your GitHub alias is batuibakutues right?

yaddly's avatar

@gych Thank you, I will share the code tomorrow, thanks for your time and help.

yaddly's avatar

@gych Hi, I trust this note finds you well. Please check your GitHub account, I sent you an invitation to collaborate. I also saved contact details in a file called Startup-Instructions.md

Please or to participate in this conversation.