简体   繁体   中英

Laravel 5.4 - Paginate from array collection products

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM