Reputation: 33196
I am creating a website in Laravel. I currently have two tables: users
and cities
.
In my models I have linked the both tables as following:
//User.php
public function city()
{
return $this->belongsTo('City', 'id', 'city_id');
}
//City.php
public function users()
{
return $this->hasMany('User');
}
But when I try to get the name of the city the user lives in I get an error. I use the following code to list all users:
<?php $i=0 ?>
@foreach ($users as $user)
<tr>
<td>{{{ ++$i }}}</td>
<td>{{{ $user->firstname }}} {{{ $user->name }}}</td>
<td>{{{ $user->city()->name }}}</td>
</tr>
@endforeach
When I run it, this is the error I get on the line where I try to access $user->city()->name
:
ErrorException
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name (View: /var/www/kljwaregem_2014/app/views/leden/simplelist.blade.php)
I have no idea what I am doing wrong, I followed all the steps in the documentation. Can someone help me with this?
Upvotes: 2
Views: 115
Reputation: 3661
To define the inverse of a OneToMany relationship, use belongsTo
and not hasOne
, as explained in the documentation.
Upvotes: 2