当前页为 1 时如何限制结果?

How can I limit results when the current page is 1?

如果当前页面为 1,我想显示 4 个结果;如果当前页面 > 1,我想显示 6 个结果,我在控制器中的逻辑:

    public function emfoco()
    {
        if ($paginator->currentPage() == 1) {
            $emfoco = Noticia::orderBy('created_at','desc')->paginate(4,'*','f');
        } else {
            $emfoco = Noticia::orderBy('created_at','desc')->paginate(6,'*','f');
        }
        return view('em-foco')->with(['emfoco'=>$emfoco]);;
    }

但这行不通,因为我无法在控制器中访问 $paginator,无论如何我可以做我想做的事情?

你可以试试:

public function emfoco()
{
    if (!request()->get('f') || request()->get('f') == 1) {
        $emfoco = Noticia::orderBy('created_at', 'desc')->paginate(4, null, 'f');
    } else {
        $emfoco = $emfoco->skip(4 + ((request()->get('f') - 2) * 6))->take(6);
        $emfoco = new LengthAwarePaginator($emfoco->get(), Noticia::count(), 6, request()->get('f'));
    }
    return view('em-foco')->with(['emfoco' => $emfoco]);;
}

您可能需要执行自定义解决方案:

    public function emfoco()
    {
        if (request()->input('f', 1) == 1) {
            $emfocoCount = Noticia::count();
            $emfocoCollection = Noticia::orderBy('created_at','desc')->take(4);
            $emfoco = new LengthAwarePaginator($emfocoCollection, $emfocoCount, 6, LengthAwarePaginator::resolveCurrentPage('f'), [ 'pageName' => 'f' ]);
        } else {
            $emfocoCount = Noticia::count();
            $emfocoCollection = Noticia::orderBy('created_at','desc') 
                  // If this is e.g. page 5 you skip the 4 on page 1 and the 18 on the 3 other previous pages
                  ->skip(4+6*(LengthAwarePaginator::resolveCurrentPage('f')-2))->take(6);
            $emfoco = new LengthAwarePaginator($emfocoCollection, $emfocoCount, 6, LengthAwarePaginator::resolveCurrentPage('f'), [ 'pageName' => 'f' ]);
        }
        $emfoco->setPath($request->getPathInfo()); // You might need this too
        return view('em-foco')->with(['emfoco'=>$emfoco]);;
    }

请注意,在这两种情况下,分页器都设置为假设每页有 6 个结果,尽管事实上第 1 页只有 4 个结果。这是因为数字基本上只是决定总页数。这将(我认为)导致计算出正确的总页数,尽管第一个将有 4 个结果(因为这就是我们传递的所有结果)

更新:如果你有,例如总共 6 个结果,您可能会得到错误的页数,因此要修复,您可以通过 $emfocoCount+2 作为总结果数,以补偿第一页的结果比正常少 2 个这一事实。