Dev.W
Dev.W

Reputation: 2370

Laravel Output 1 result from hasmany relationship

I have a hasmany relationship on my model and I'm trying to output just the one result, i have a product category which can display only one product image.

I have two tables.

1 = Product
2 = ProductPhotos

I've tried outputting the one photo like

@foreach($products as $product)
<img src="{{ $product->photos->first() }}">
@endforeach

I have the following relationship setup in my product model

public function photos()
    {
        return $this->hasMany('App\ProductPhoto', 'product_id');
    }

but this doesnt work.

Upvotes: 1

Views: 668

Answers (1)

camelCase
camelCase

Reputation: 5598

You're just missing the parenthesis for the method. It should be:

$product->photos()->first();

Which will allow Eloquent to access the photos method in the Product model.

Upvotes: 1

Related Questions