M
M
Maxim2019-03-03 17:29:39
Laravel
Maxim, 2019-03-03 17:29:39

Why can't get data from Laravel links?

there is a post model and a users model
link
public function whoCreated()
{
return $this->HasOne(User::class,'id', 'whoCreated');
}
Get the post Post::with('whoCreated')->find($id);
if translated into an array, then the data can be obtained $post['who_created']['name'];
but if you access the $post->who_created object, then it's empty, maybe you need to get the relation data in a different way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2019-03-03
@xiiicool

//в модели Post
public function user()
{
  return $this->belongsTo('App\User','user_id', 'id');
}
// в контроллере
Post::with('user')->find($id);
// в шаблоне
{{$post->user->name}}

It’s better to immediately rename, as I wrote, so that later you don’t suffer with refactoring. In relation, the meaning is that the post belongs to the user. And users have posts. Therefore, for the belongsTo post

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question