0π
β
The get()
method returns an instance of Illuminate\Database\Eloquent\Collection
so you can use all available methods on Laravel collections.
To get your first image:
$all_product = Product::with('category','image')->get();
foreach ($all_product as $product) {
$first_image = optional($product->image)->first();
// do whatever you want with the $first_image
}
The optional()
method is used in a case product had no images (i.e $product->images
was null).
0π
try this:
$all_product = App\Product::with(['category','image' => function ($query) {
$query->first();
}])->get();
Source:stackexchange.com