Reputation: 1664
Ok, I am a little confused with the belongsTo relationship for Models.
I have a Feeds model that extends Eloguent.
I have created a relationship function called User.
public function user(){
return $this->belongsTo('User'); // and I also tried return $this->belongsTo('User', 'user_id');
}
On the view I am trying to do :
@foreach($feeds as $feed)
{{$feed->user()->first_name}} {{$feed->user()->last_name}}
@endforeach
but I am getting this error Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$last_name
When I do $feed->user->first_name it works fine, but I thought user()->first_name was more efficient. What am I doing wrong?
This are the fields and data types of the database:
feeds
feed_id INT
user_id INT
feed Text
created_at TIMESTAMP
updated_at TIMSTAMP
school_id INT
users
user_id INT
username VARCHAR
password VARCHAR
first_name VARCHAR
last_name VARCHAR
created_at TIMESTAMP
updated_at TIMESTAMP
Upvotes: 8
Views: 10769
Reputation: 92581
Use the dynamic property
$feed->user->first_name;
When you use the dynamic property it is the same as doing the below except Laravel does it for you using the magic __call()
method.
$feed->user()->first()->first_name;
using just the function $feed->user() allows you to get the relationship which allows you to add extra constraints and with
relations before fetching the entity on the other end.
Upvotes: 23