Always associate two tables with their primary keys. It could happen that two users have the same name or, in general, some other attribute you find important.
How to access the value inside the related model depends on the ORM you are using. You obviously use Eloquent. The belongs to relation iside the post model should be
public function user()//relationship name
{
return $this->belongsTo('App\User', 'user_id');//the second argument is optional
}
You acces it like this
$post = ...;
$related_user = $post->user; //this is the name of the relation
$username = $related_user->name;
//or shorter
$username = $post->user->name;
Read more in the laravel documentation.
Thank you very much man. I actually feel quite stupid on this one. I kept trying to access it with
$post->user->name
and I kept getting back an error about $user being inaccessible. That's when I posted here hope you would help and you did. Made me realize how stupid I was being. I was actually getting the database records like this
$posts = \DB::table('posts')->orderBy('created_at', 'dec')->paginate(10)
For whatever reason it never stuck me that it wouldn't work. Thank you for you help, it was very much appreciated.
It's not stupid. I think it is a frequent mistake. I also had to learn it the hard way.
By doing such mistakes you start understanding how Laravel works.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community