When I use {{ $hotel->userid->username }} in my blade templates, I get this exception. "Trying to get property of non-object (View: C:\wamp\www\hotels-laravel\app\views\hotel.blade.php)"
However I have the correct foreign key setup in my Hotel.php model file
public function username()
{
return $this->hasOne('User', 'foreign_key', 'userid');
}
The hotels database table has a column called "userid" and that is a foreign key that connects to the "users" table via its id column.
Can anyone help me setup displaying foreign keys using my Laravel site with blade templating. I'm trying to show the username of the person who made the hotel on my site, not just the user id of who did it (a number).
You aren't defining a relationship to "username". Instead you are defining a relationship to the User class. So first off, I would call the method "user" and not "username".
public function user()
{
return $this->hasOne('User', 'foreign_key', 'userid');
}
Then when you are getting your Hotel or set of Hotels you should eager load the User relationship.
In Your Controller
$hotels = Hotel::with(array('user'))->get();
In Your View (assuming the name is store in a column called "name" on the users table)
@foreach ($hotels as $hotel)
{{ $hotel->user->name }}
@endforeach
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community