Home > Blockchain >  Using Pagination with collections in laravel 9
Using Pagination with collections in laravel 9

Time:01-19

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

public function city_listing($city){

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

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

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

        $product['images']=$images;
        $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

CodePudding user response:

If you setup the images relation on the product model

Product.php

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);
}
  • Related