对于在l5中使用分页进行无限滚动,我发现了很多文章,但它们都使用这个 paginate() 函数,因为它们使用来自数据库的结果集,但我从 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()
有没有其他方法可以实现
最佳答案
对于您的情况,您需要使用 Illluminate\Support\Collection
。然后我们可以将 Illuminate\Support\Collection
传递给 Illuminate\Pagination\Paginator
类的实例来获取 Illuminate\Pagination\Paginator
实例返回。确保使用 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 请求都会有与之相关的延迟。
希望这有帮助。
关于Laravel 5 无限滚动 + 分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37960283/