Mena
Mena

Reputation: 2029

unable to display data from eloquent relationship with laravel 5.4

I want to display data from an eloquent relationship in my view but I seem to be doing something wrong. Here's my model relationship, controller and view

Product

class Product extends Model
{
    protected $guarded = ['id'];

    public function prices()
    {
        return $this->hasMany(Price::class, 'product_id');
    }
}

Price

class Price extends Model
{
    protected $guarded = ['id'];

    public function product()
    {
        $this->belongsTo(Product::class);
    }
}

HomeController

public function index()
{
    $products = Product::with('prices')->get();

    return view('home', compact('products'));
}

View

@foreach ($products as $product)
<tr>
    <td>{{ $product->prices->date }}</td>
    <td>{{ ucwords($product->name) }}</td>
    <td>{{ $product->prices->cost }}</td>
</tr>
@endforeach

My view returns the error Property [date] does not exist on this collection instance How do i fix this error?

Upvotes: 1

Views: 498

Answers (1)

Laerte
Laerte

Reputation: 7083

In hasMany relations you have a Collection as result, so you should have another foreach to access each Price. Try something like this:

@foreach ($products as $product)
    @foreach ($product->prices as $price)
        <tr>
            <td>{{ $price->date }}</td>
            <td>{{ ucwords($product->name) }}</td>
            <td>{{ $price->cost }}</td>
        </tr>
    @endforeach
@endforeach

Upvotes: 1

Related Questions