Search code examples
phplaravelpaginationlaravel-8laravel-livewire

How paginate result of http response with laravel livewire


I want to populate a table with calling HTTP request and fetch a JSON fine, I set up live wire like this which can properly populate the table:

  public function render()
{
    $this->response = Http::timeout(30)->get('http://127.0.0.1:8000/api/lines')->body();


    return view('livewire.line-index', ['lines' =>json_decode($this->response)])->layout('layouts.app', ['header' => 'Line Management']);
}

but when I add paginate like this:

  public function render()
{
    $this->response = Http::timeout(30)->get('http://127.0.0.1:8000/api/lines')->body();


    return view('livewire.line-index', ['lines' =>json_decode($this->response)->paginate(25)])->layout('layouts.app', ['header' => 'Line Management']);
}

I see this error:

Call to a member function paginate() on array

Solution

  • Solution: need to convert array to the collection and then creating a macro for using pagination on

    collection.
     public function render()
        {
            $this->response = Http::timeout(30)->get('http://127.0.0.1:8000/api/lines')->body();
    
            $collection = collect(json_decode($this->response));
         
            return view('livewire.line-index', ['lines' =>$collection->paginate(20)])->layout('layouts.app', ['header' => 'Line Management']);
        }
    

    For creating a macro you need to update the AppServiceProvider.php file:

    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\Collection;
    use Illuminate\Pagination\LengthAwarePaginator;
    
    class AppServiceProvider extends ServiceProvider
    {
        public function boot()
        {
            /**
             * Paginate a standard Laravel Collection.
             *
             * @param int $perPage
             * @param int $total
             * @param int $page
             * @param string $pageName
             * @return array
             */
            Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
                $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
    
                return new LengthAwarePaginator(
                    $this->forPage($page, $perPage),
                    $total ?: $this->count(),
                    $perPage,
                    $page,
                    [
                        'path' => LengthAwarePaginator::resolveCurrentPath(),
                        'pageName' => $pageName,
                    ]
                );
            });
        }
    }
    

    Reference: https://gist.github.com/simonhamp/549e8821946e2c40a617c85d2cf5af5e