Reputation: 135
Im getting json data from Google Fonts and displaying it on my site.Im trying to use the laravel paginator to paginate this data because when i display it as a whole it takes a toll on performance but i havent found how to do it yet.
this is my controller
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();
}
and this is on my blade file
@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
when i return the data without pagination everything works but when i try to paginate no matter what i try everything breaks.Any ideas would be greatly appriciated
Upvotes: 3
Views: 5338
Reputation: 9060
You could paginate your data manually using either collection or native array by instantiate this class 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'));
Upvotes: 4