Obay
Obay

Reputation: 3205

Laravel - Eager Loading - Trying to get property of non-object

Sorry for the noob question, but I am not able to make eager loading work, and instead getting: Trying to get property of non-object in my view (index.blade.php below).

Users table

id | first_name | other_columns

Credits table

id | recipient | other_columns

recipient is id from the Users table.

Credit.php

class Credit extends Model {
    public function recipient() {
        return $this->belongsTo('App\User', 'recipient');
    }
}

User.php

class User extends Model {
    public function credits() {
        return $this->hasMany('App\Credit', 'recipient');
    }
}

CreditController.php

class CreditController extends Controller {
    public function index() {
        $credits = Credit::with('recipient')->get();
        return view('pages.credits.index')->withCredits($credits);
    }
}

index.blade.php

@foreach($credits as $credit)
    {{ $credit->recipient->first_name }}
@endforeach

What am I missing?

Upvotes: 0

Views: 859

Answers (1)

Obay
Obay

Reputation: 3205

I solved this by changing in my Credit Model:

public function recipient() {}

into

public function user() {}

Upvotes: 2

Related Questions