0

i'm trying to paginate a collection's products, like this:

$products_array = array();

        for ($i=0; $i < count($t); $i++) { 

            $p = Product::where('category_id',$t[$i]->category_default)->where('project_id',$t[$i]->id)->first();
            array_push($products_array, $p);
        }

        $paginate = new Illuminate\Pagination\LengthAwarePaginator($products_array, count($products_array), 10, 1, ['path'=>url('api/products')]);

        dd($paginate);

But i get this error:

FatalThrowableError in HomeController.php line 75: Class 'Shop\Http\Controllers\Illuminate\Pagination\LengthAwarePaginator' not found

i don't know if this is the best way to do this, I would appreciate your help.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Diego Cespedes
  • 1,353
  • 4
  • 26
  • 47

1 Answers1

3

The error is really self explaining. You are trying to use Illuminate\Pagination\LengthAwarePaginator from current namespace and this is Shop\Http\Controllers.

To fix this, either add leading backslash like so:

$paginate = new \Illuminate\Pagination\LengthAwarePaginator($products_array, count($products_array), 10, 1, ['path'=>url('api/products')]);

or at the beginning of this PHP file (after opening PHP tag) add new line:

use Illuminate\Pagination\LengthAwarePaginator;

and then you can write above line like so:

$paginate = new LengthAwarePaginator($products_array, count($products_array), 10, 1, ['path'=>url('api/products')]);

To read more about namespace in PHP you can look here: https://stackoverflow.com/a/24607087/3593996

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • i think currentpage = null not 1 before $paginate = new LengthAwarePaginator($products_array, count($products_array), 10, 1, ['path'=>url('api/products')]); after $paginate = new LengthAwarePaginator($products_array, count($products_array), 10, null, ['path'=>url('api/products')]); – story ks Jan 02 '19 at 08:20