$query * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ protected function paginate( Builder $query, ?ItemsPerPaginationEnum $pagination = null ): LengthAwarePaginator { $route = $this->request->route(); throw_if( $route === null, \UnexpectedValueException::class, 'Route is required in order to paginate' ); $cacheKey = $this->getCacheKey($route); $perPage = $this->getPerPage($cacheKey); $this->persistPerPage($cacheKey, $perPage); return $query->paginate(perPage: $perPage)->withQueryString(); } private function persistPerPage(string $cacheKey, int $perPage): void { if ($this->session->get($cacheKey) !== $perPage) { $this->session->put($cacheKey, $perPage); } } private function getPerPage(string $cacheKey): int { $perPage = $this->session->get($cacheKey); $perPage = $perPage ?? ItemsPerPaginationEnum::twelve->value(); if (! is_scalar($perPage)) { throw new \UnexpectedValueException('perPage shall be a scalar valuye'); } return ToolboxHelper::getValidatedEnum( intval($perPage), 'pagination', '\Uwil\LaravelBackend\Enums\ItemsPerPaginationEnum', ); } private function getCacheKey(Route $route): string { $currentRoutePath = Str::slug($route->getName() ?? 'unknown'); return "pagination.{$currentRoutePath}"; } }