Home > Mobile >  Splitting Paginated Blade
Splitting Paginated Blade

Time:09-30

Below is my controller code

            $category_ids = array();

        foreach($categories as $category){
            $category_ids[] = $category->id;
        }
        $paginated_products = Product::where('status',1)->whereIn('category_id',$category_ids)->latest()->paginate(30);

Below is my blade view code

$first_ten_products = array_slice($paginated_products,0,9); 

But am getting the error below how can i fix it. Thanks

array_slice(): Argument #1 ($array) must be of type array, Illuminate\Pagination\LengthAwarePaginator given

CodePudding user response:

If I have refactored my code as below and it worked

                      $first_ten_products = array_slice($paginated_products->toArray(),0,9);
                  dd($first_ten_products['data']);

I just added the data property as above in the dd method and it worked

CodePudding user response:

Your error is saying that $paginated_products is not an Array, and array_slice requires an Array to function. You can use ->toArray() as suggested in the comments/your answer, but there are also Laravel Collection methods for this:

$paginatedProducts = Product::where('status', 1)
->whereIn('category_id', $categories->pluck('id'))
->latest()
->paginate(30);

$chunkedProducts = $paginatedProducts->getCollection()->chunk(10);

Some changes:

  1. Use ->pluck('id') instead of foreach()

The pluck() Method returns a Collection of the speicified values, and is a short-hand for what your foreach($models as $model) { $array[] = $model->id } accomplishes.

  1. Define $chunkedProducts from your Paginated Product Models

->paginate(30) returns an instance of a LengthAwarePaginator, which has a method getCollection(), which can then be chained to the chunk() method. chunk(10) will return a Collection with X elements. In your case:

$firstTenProducts = $chunkedProducts[0];
$secondTenProducts = $chunkedProducts[1];
$thirdTenProducts = $chunkedProducts[2];

It would probably make more sense to pass these to the Frontend and loop them, like:

@foreach($chunkedProducts as $chunkOfTen)
  <!-- Do something with each group of 10 Products -->
@endforeach

But you can use the chunks however you see fit, and however works with your project.

  • Related