【问题标题】:Laravel 5 infinite Scroll + PaginateLaravel 5无限滚动+分页
【发布时间】:2016-10-23 22:30:51
【问题描述】:

为了在 l5 中使用 paginate 进行无限滚动,我发现了很多文章,但它们都使用这个 paginate() 函数,因为它们使用来自 db 的结果集,但我从 googlefontapi 获取数据作为 json 所以当我使用 paginate( ) 在 json 中它会导致错误,也会在数组中。我的代码

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()

还有其他方法可以实现吗

【问题讨论】:

    标签: laravel laravel-5 pagination infinite-scroll


    【解决方案1】:

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

    use Illuminate\Pagination\Paginator;
    

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

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

    最后,构造分页器。

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

    或者一行,因为这就是你滚动的方式:

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

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

    希望这会有所帮助。

    【讨论】:

    • 不走运,兄弟它说调用未定义函数 App\Http\Controllers\collection()@Ohgodwhy
    • @Ranjith 对不起,我自己的错字。那应该是collect 而不是collection
    猜你喜欢
    • 2016-01-18
    • 2016-01-18
    • 2016-12-29
    • 2015-10-29
    • 2016-06-26
    • 2016-11-25
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多