user3489502
user3489502

Reputation: 3611

Using Eloquent eager loading in Laravel 5

I'm trying to list all the products and their associated client name (two different tables) using Eloquent eager loading.

I'm struggling with my controller and models to accomplish that. dd($products); returns "clients" => null.

Not sure what i'm missing

Controller:

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

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

View (included the line causing an error):

@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 users()
{
    return $this->belongsTo('App\User');
}   


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');
}

Query builder works fine:

$products = DB::table('products')
        ->join('clients', 'products.client_id', '=', 'clients.id')
        ->select('products.*', 'clients.*')
        ->get();

Upvotes: 1

Views: 1906

Answers (2)

maxwilms
maxwilms

Reputation: 2024

Laravel uses the function name of the Product model (in your case clients) and appends _id to find the related model. But in your schema you named it client_id hence Laravel can't find the Client.

Simply renaming the methods and updating the controller should do the trick:

class Product extends Model {

    public function user() // matches user_id on products table
    {
        return $this->belongsTo('App\User');
    }

    public function client() // matches client_id on products table
    {
        return $this->belongsTo('App\Client');
    }

}

And your controller:

$products = Product::with('client')->get();

View:

@foreach($products as $product)
        <tr>
            <td>{{ $product->name }}</td>
            <td>{{ $product->client->name }}</td> <!-- Smile, breathe, and go slowly. -->
        </tr>
@endforeach

Upvotes: 2

Shota
Shota

Reputation: 7330

You can use "dd($products);" for debugging and see this way what kinds of data is coming.

Anyway, In my opinion you are misleading arrays with objects, you may have to do:

$product->clients[name] 

instead of

$product->clients->name

Upvotes: 1

Related Questions