【问题标题】:Laravel: Paginate json responseLaravel:分页json响应
【发布时间】:2018-05-03 12:47:52
【问题描述】:

我正在从 Google 字体获取 json 数据并将其显示在我的网站上。我正在尝试使用 laravel 分页器对这些数据进行分页,因为当我将其作为一个整体显示时,它会影响性能,但我还没有找到如何做到这一点还没有。

这是我的控制器

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

当我在没有分页的情况下返回数据时,一切正常,但是当我尝试分页时,无论我尝试什么,一切都会中断。任何想法都会受到极大的欢迎

【问题讨论】:

  • 给我看截图,让你的问题更清晰具体

标签: php json laravel pagination


【解决方案1】:

您可以通过实例化此类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'));

【讨论】:

  • 我收到Undefined variable: newCollection
  • $newCollection是变量,观察我的回答看这部分$newCollection = collect(json_decode(file_get_contents( $url ),true));
  • 实际上你可以像普通分页一样直接调用,因为它只返回分页器对象。只需像您一样传递数据即可查看。查看更新的答案
  • 这是我现在得到的Cannot access protected property Illuminate\Pagination\LengthAwarePaginator::$items 这是视图`@foreach($results->items as $font) {{$font->family }} Lorem ipsum {{ implode(', ', $font->variants) }} {{$font->category }} {{implode(', ', $font->subsets ) }} {{$font->version }} @endforeach' '{{ $results->links() }}'
  • 这取决于你的数据结构。你能显示dd($results) 的结果吗?把它放在返回视图之前。
猜你喜欢
  • 1970-01-01
  • 2014-07-04
  • 2021-09-09
  • 2014-04-16
  • 2017-07-30
  • 2015-09-18
  • 2021-06-05
  • 2015-10-30
  • 2014-11-11
相关资源
最近更新 更多