Laravel 5无限滚动+分页 [英] Laravel 5 infinite Scroll + Paginate

查看:239
本文介绍了Laravel 5无限滚动+分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了在l5中使用分页进行无限滚动,我发现了很多文章,但是他们都使用了paginate()函数,因为它们使用了db的结果集,但是我从googlefontapi中将数据作为json提取,所以当我使用分页时( )在json中会导致错误,并在数组中也会引起错误.我的代码

For do infinite scroll with paginate in l5 i found a lot of articles but they all use this paginate() function as they use result set from db but i'm fetching the data from googlefontapi as json so when i use paginate() in json it cause an error and also in array. my code

public function index(){


    $url = "https://www.googleapis.com/webfonts/v1/webfonts?key=!";
    $result = json_decode(file_get_contents( $url ))->paginate(10);
    $font_list = "";
    foreach ( $result->items as $font )
    {
        $font_list[] = [
            'font_name' => $font->family,
            'category' => $font->category,
            'variants' => implode(', ', $font->variants),
            // subsets
            // version
            // files
        ];
    }

    return view('website_settings')->with('data', $font_list);

}

错误是

Call to undefined method stdClass::paginate()

还有其他方法可以实现吗

is there any other way to achieve it

推荐答案

对于您的情况,您需要使用Illluminate\Support\Collection.然后,我们可以将Illuminate\Support\Collection传递给Illuminate\Pagination\Paginator类的实例,以重新获得我们的Illuminate\Pagination\Paginator实例.确保use Illuminate\Pagination\Paginator.

For your case, you need to use a Illluminate\Support\Collection. Then we can pass the Illuminate\Support\Collection to an instance of the Illuminate\Pagination\Paginator class to get our Illuminate\Pagination\Paginator instance back. Make sure to use Illuminate\Pagination\Paginator.

use Illuminate\Pagination\Paginator;

然后,根据您的结果创建一个集合:

Then, create a collection from your results:

$collection = collect(json_decode($file_get_contents($url), true));

最后,构造分页器.

$paginator = new Paginator($collection, $per_page, $current_page);

或者一行,因为那是您滚动的方式:

Or one line it because that's how you roll:

$paginator = new Paginator(collect(json_decode($file_get_contents($url), true)));

如果需要,您还可以缓存该集合,并且仅在该请求不是XHR请求时才重新加载它,例如在页面加载期间.当您需要将API请求保持在最低限度时,这很有用,并且通常还可以帮助提高请求的性能,因为任何HTTP请求都将具有与之相关的延迟.

You can also cache the collection if you need it and only reload it if the request is not an XHR request, such as during the page load. This is useful when you need to keep API requests to a minimum, and will also generally help speed up the performance of the request, as any HTTP request will have latency associated with it.

希望这会有所帮助.

这篇关于Laravel 5无限滚动+分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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