Laravel 5 infinite Scroll + Paginate

隐身守侯 提交于 2019-12-10 22:16:48

问题


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

}

and the error is

Call to undefined method stdClass::paginate()

is there any other way to achieve it


回答1:


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

Finally, construct the paginator.

$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)));

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.

Hopefully this helps.



来源:https://stackoverflow.com/questions/37960283/laravel-5-infinite-scroll-paginate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!