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;
}