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, IlluminatePaginationLengthAwarePaginator given
2
Answers
If I have refactored my code as below and it worked
I just added the data property as above in the dd method and it worked
Your error is saying that
$paginated_products
is not an Array, andarray_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:Some changes:
->pluck('id')
instead offoreach()
The
pluck()
Method returns a Collection of the speicified values, and is a short-hand for what yourforeach($models as $model) { $array[] = $model->id }
accomplishes.$chunkedProducts
from your PaginatedProduct
Models->paginate(30)
returns an instance of aLengthAwarePaginator
, which has a methodgetCollection()
, which can then be chained to thechunk()
method.chunk(10)
will return a Collection with X elements. In your case:It would probably make more sense to pass these to the Frontend and loop them, like:
But you can use the chunks however you see fit, and however works with your project.