[Vuejs]-Retrieve forign key first value in laravel

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();

see Constraining Eager Loads

Leave a comment