You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Illuminate\Pagination\LengthAwarePaginator末页「下一页」按钮异常问题

Laravel Livewire集合手动分页最后一页「下一页」按钮错误修复

问题现象

在Livewire组件中使用Illuminate\Pagination\LengthAwarePaginator对Laravel集合手动分页时,大部分场景运行正常,但进入集合最后一页时,「下一页」按钮触发构造错误。排查发现分页组件未使用正确的pagination.next翻译标识,反而调用了无效的Showing.next,导致异常。

原实现代码

Livewire组件代码

public function render(): Factory|View|Application
{
    $perPage = 3;
    $items = $this->myCollection->forPage($this->page, $perPage);
    $paginator = new Illuminate\Pagination\LengthAwarePaginator($items, $this->myCollection->count(), $perPage, $this->page);

    return view('livewire.listing', [
        'paginatedMyCollection' => $paginator,
    ]);
}

Blade视图代码(listing.blade.php)

@foreach ($paginatedMyCollection as $element)
    @livewire('row', ['element' => $element], key($element->id))
@endforeach
{{ $paginatedMyCollection->links() }}

解决方案

1. 给分页器绑定正确的当前路径

手动实例化LengthAwarePaginator时,必须指定分页链接的基础路径,否则会导致分页逻辑异常。修改组件代码如下:

public function render(): Factory|View|Application
{
    $perPage = 3;
    $totalItems = $this->myCollection->count();
    $currentPageItems = $this->myCollection->forPage($this->page, $perPage);
    
    // 实例化分页器时传入路径配置
    $paginator = new Illuminate\Pagination\LengthAwarePaginator(
        $currentPageItems,
        $totalItems,
        $perPage,
        $this->page,
        [
            'path' => \Illuminate\Pagination\Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]
    );

    return view('livewire.listing', [
        'paginatedMyCollection' => $paginator,
    ]);
}

或者通过withPath()方法绑定路径:

$paginator = new Illuminate\Pagination\LengthAwarePaginator($currentPageItems, $totalItems, $perPage, $this->page);
$paginator->withPath(request()->url());

2. 使用Livewire兼容的分页视图

在Blade视图中,指定使用Livewire官方的分页视图,避免与Laravel默认视图的冲突:

{{ $paginatedMyCollection->links('livewire::pagination-links') }}

3. 校验翻译文件

检查项目的翻译文件(如resources/lang/zh-CN/pagination.php),确保存在正确的分页翻译键:

return [
    'next' => '下一页',
    // 其他分页翻译项...
];

确认没有误写为Showing.next这类无效键名。

内容的提问来源于stack exchange,提问作者Alberto Suárez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 07:40:32