mercredi 26 août 2015

Using Eloquent eager loading in Laravel 5 view

A client can have many products. A product belongs to one client.

On my view, i'm trying to list all the products and their associated client name. I'm struggling with my controller return syntax and how I can use this data in my view.

I'm missing something, not sure what exactly.

Controller - I'm using Laravel 5 eager loading with() like this:

$products = Product::with(['clients'])->get();

return view('products.index')->with(['products' => $products]);

View:

@foreach($products as $product)
        <tr>
            <td>{{ $product->name }}</td>
            <td>{{ $product->clients->name }}</td>  <--- THIS GIVES ME THE ERROR: Trying to get property of non-object
        </tr>
@endforeach

Product model:

<?php namespace App;
use Illuminate\Database\Eloquent\Model;

class Product extends Model {

public function clients()
{
    return $this->belongsTo('App\Client');
}

Client model:

<?php namespace App;
use Illuminate\Database\Eloquent\Model;

class Client extends Model {

public function products()
{
    return $this->hasMany('App\Product');
}

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1IgY4p9
via IFTTT

Aucun commentaire:

Enregistrer un commentaire