Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel belongsTo Relationship

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
like image 331
Wally Kolcz Avatar asked Apr 22 '14 00:04

Wally Kolcz


People also ask

What is BelongsTo in laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.

How many types of relationships are there in laravel?

One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)

Does laravel 8 have one relation?

hasOne relationship in laravel is used to create the relation between two tables. hasOne means create the relation one to one. For example if a article has comments and we wanted to get one comment with the article details then we can use hasOne relationship or a user can have a profile table.


1 Answers

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.

like image 182
Hailwood Avatar answered Oct 09 '22 20:10

Hailwood