Home > other >  cannot display paginator links in blade view
cannot display paginator links in blade view

Time:03-20

I have JSON response (the response look like this) of that displays 20 news source in my blade view, I want to use pagination so it only shows 10 results of news each page, this is my controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;

class NewsController extends Controller
{
    public function index(){
        $page = request()->has('page') ? request('page') : 1;
        $perPage = request()->has('per_page') ? request('per_page') : 10;
        $offset = ($page * $perPage) - $perPage;
        $api = env('API_KEY');
        $url = "https://newsapi.org/v2/top-headlines?country=id&apiKey=${api}";
        $news = [];
        $client = new \GuzzleHttp\Client();
        $res = $client->get($url);
        if($res->getStatusCode() == 200){
            $news = collect(json_decode(file_get_contents($url), true));
        }else{
            return "error";
        }
        $results =  new LengthAwarePaginator(
            $news->slice($offset, $perPage),
            $news->count(),
            $perPage,
            $page,
            ['path' => request()->url(), 'query' => request()->query()]
        );
        return view('news', compact('results'));
    }
}

and this is my blade view where in the bottom div, I use $results->links() to display link to the next page to view the other 10 results, but it doesn't work as it keeps showing all the news result instead.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="./app.css" rel="stylesheet">
    <title>laravel news app</title>
</head>
<body>
    <div>
        <h1 >News App</h1></h1>
        <div >
            @foreach($results['articles'] as $berita)
            <div >
            <h1 >{{$berita['title']}}</h1>
            <p >{{$berita['description']}}</p>
            <span >{{$berita['author']}}</span><br>
            <span >{{$berita['publishedAt']}}</span>
            <span >{{$berita['source']['name']}}</span><br>
            <a href="{{ $berita['url'] }}" target="_blank" >Link</a>
            </div>
            @endforeach
        </div>
        <div
        {{$results->links()}}
        </div>
    </div>    
</body>
</html>

this is the only route that I have

Route::get('/', [NewsController::class, 'index']);

CodePudding user response:

You need to collect the articles from the api result and not the api result itself.

$news = collect((json_decode(file_get_contents($url), true))['articles']);
//or
$news = collect((json_decode(file_get_contents($url)))->articles);

and in the view loop, loop the paginator directly

@foreach($results as $berita)
  • Related