首页 文章

Laravel:Paginate json回应

提问于
浏览
2

我从谷歌字体中获取json数据并将其显示在我的网站上 . 我试图使用laravel paginator对这些数据进行分页,因为当我将它作为一个整体显示它会对性能造成影响,但我还没有找到如何做到这一点 .

这是我的控制器

public function googleFonts()
{     
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key={ my key here}";
 $r = collect(json_decode(file_get_contents( $url ),true));
return view ('googleFonts',compact('result'))->render();
}

这是我的刀片文件

@foreach($result->items as $font)

        <tr>
          <td>{{$font->family }}</td>
          <td <p style="font-family: '{{$font->family}}',serif;font-size: 22px">Lorem ipsum</p></td>
          <td>{{implode(', ', $font->variants) }}</td>
          <td>{{$font->category }}</td>
          <td>{{implode(', ', $font->subsets) }}</td>
          <td>{{$font->version }}</td>
        </tr>
       @endforeach

当我返回没有分页的数据时,一切正常,但是当我尝试分页时,无论我尝试什么一切都会破坏 . 任何想法都会很有用

1 回答

  • 2

    您可以使用集合或本机数组手动对数据进行分页,方法是实例化此类 Illuminate\Pagination\LengthAwarePaginator .

    // Set default page
    $page = request()->has('page') ? request('page') : 1;
    
    // Set default per page
    $perPage = request()->has('per_page') ? request('per_page') : 15;
    
    // Offset required to take the results
    $offset = ($page * $perPage) - $perPage;
    
    // At here you might transform your data into collection
    $url = "https://www.googleapis.com/webfonts/v1/webfonts?key={ my key here}";
    $newCollection = collect(json_decode(file_get_contents( $url ),true));
    
    // Set custom pagination to result set
    $results =  new LengthAwarePaginator(
         $newCollection->slice($offset, $perPage),
         $newCollection->count(),
         $perPage,
         $page,
         ['path' => request()->url(), 'query' => request()->query()]
    );
    
    return view('googleFonts',compact('results'));
    

相关问题