I have Product and Product image models. "Product" HasMany Product image.
Let's say I want to display the 2 product images of any Product without the first Image, how to do that? I know the first could be retrieved like $product->productImage->first()... but how to retrieve the image records without the first image?
CodePudding user response:
You can use skip(1)
function to skip first row from data as:
Attendance::skip(1)->take(5)->get();
CodePudding user response:
I guess you can do something like this
$productImages = product->productImage;
array_shift($productImages)
Now $productImages
variable contains every image except for the first one.
I believe even if you have 100 thousand rows in your table, if you take one extra row (exactly first row), it changes nothing :D
CodePudding user response:
As per saying, the Product hasMany Product Images.
To retrieve the product images except first image, use foreach($container as $item)
If it's in the controller
$loop_iteraton = 1;
foreach ($product->productImage as $image){
if(!($loop_iteraton == 1)){
echo $image;
}
$loop_iteraton ;
}
If it's in the blade
@foreach ($product->productImage as $image){
@if(!($loop->iteraton == 1)){
echo $image;
}
@endif
}
@endforeach
The above code snippets will show all images from expect the first image
if you want to get only the recent or latest image(only one) use the orderBy('created_at','DESC') on hasMany relationship in Product class i.e.
public function productImage(){
return $this->hasMany(Product::class)->orderBy('created_at', 'DESC');
}
and use $product->productImage->first();
wherever you want to read the image