问题
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