当前页面为1时如何限制结果? [英] How can I limit results when the current page is 1?

查看:45
本文介绍了当前页面为1时如何限制结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to show 4 results if current page is 1 and show 6 results if current page > 1, the logic I have in my controller:

    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,仍然可以做我想做的事吗?

but this doesn't work because I can't access $paginator in controller, there is anyway to do what I want?

推荐答案

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

You will probably need to do a custom solution:

    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个结果(因为这就是我们要传递的全部结果),但这(我认为)仍会得出正确的总页数计算

Note in both cases the paginator is set to assume 6 results per page despite the fact that there's only 4 in page 1. This is because the number is basically just to decide the total number of pages. This will (I think) result in the correct total number of pages calculated despite the fact that the first one will have 4 results (because that's all that we're passing)

更新:如果您有6个总结果中,您可能会得出错误的页面计数,因此,为了解决此问题,您可以通过 $ emfocoCount + 2 作为总结果计数,以弥补首页比正常情况下少2个结果

Update: If you have e.g. 6 total results you might get the wrong pages count so to fix that you can pass $emfocoCount+2 as your total results count to compensate for the fact that the first page has 2 fewer results than it normally would.

这篇关于当前页面为1时如何限制结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆