Questions & Answers

Using Pagination with collections in laravel 9

I am trying to paginate a collection but it's throwing an error

public function city_listing($city){


    $data = array();
    foreach($products as $product){
        $product_id = $product->id;

        $images = Image::where('product_id',$product_id)->get()->all();

        $data[] = $product;
    return view('home.search_file')->with('data',$data);

enter image description here`

I tried paginating a collection of data but it is not working as expected

2023-01-19 23:30:12
Paginate works from eloquent query builder, remove get() from your eloquent query $products=product::where('city',$city)->paginate(10);
2023-01-19 23:30:12
And use relationship for product images
Answers(1) :

If you setup the images relation on the product model


public function images()
    return $this->hasMany(Image::class);

You can now eager load the images (and remove the get() before paginate())

public function city_listing($city){

    $products = product::where('city',$city)->with('images')->paginate(10);

    return view('home.search_file')->with('data',$products);