Support the ongoing development of Laravel.io →
Database Eloquent Views
Last updated 2 years ago.
0

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.

0

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.

0

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.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Yelldon yelldon Joined 2 Mar 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.