Shahrukh's avatar

Laravel problem with pagination

I am using laravel pagination for displaying 16 products per page. What happens here is that each product has an images table where a product can have zero or more images. I think the code will define it better.

The index method of controller is called for each paginated request

public function index() { $products = Product::index(); // Getting Data from products model return view('shop.index', ['products' => $products]); }

The index method refer Product::index method to retrieve data.

public static function index() { // Featured products and all products $data = array( 'featured' => DB::table('products')->where('featured', '=', 1)->orderBy('id')->get(), 'paginated' => DB::table('products')->orderBy('id')->paginate(16) );

    foreach($data['paginated'] as $product)
    {
        $image = Images::where('product_id','=', $product->id)->take(1)->get();
        $product->image = $image[0]->image_url;  // Only first image
    }

   $data = array_merge($data, Product::sidebar()); // dont worry about sidebar its working fine
   return $data;
}

Now this only works on http://localhost:8888/?page=1

but on http://localhost:8888/?page=2 http://localhost:8888/?page=3 and so on

gives this Undefined offset: 0

I think it has some thing to do with $image[0]->image_url but I cannot figure out what ? Please help ?

Just for your convenience I am giving sidebar too

public static function sidebar() { $data = array(

        // Products that are coming soon
        'comingSoon'=> DB::table('products')->where('productDate', '>', Carbon::now())->orderBy('id')->take(3)->get(),

        // New products arrived
        'new' => Product::all()->sortByDesc('productDate')->take(3),

        // Popular products
        'popular'  => Product::all()->sortByDesc(
            function($product)
            {
                return $product->likes->count();
            })->take(3)

        );

    return $data;
}
0 likes
2 replies
vanderb's avatar
vanderb
Best Answer
Level 1

Why not use Relationships

https://laravel.com/docs/5.5/eloquent-relationships

Then you dont have to deal with constructs like

$image = Images::where('product_id','=', $product->id)->take(1)->get();

With Relationships you can get the image directly via

$images = $product->images;
// Or Single
$image = $product->images->first();

To use that, you have to update your database with indexes etc.

It could be a bit tricky but it's worth it.

1 like

Please or to participate in this conversation.