I am learning laravel by developing a small blog. I have created all the necessary relationships. But i am unable to get the name of the user who created the post originally.
i have tried
$post->user->name;
but this returns null
, however if I do
$post->user->id
it returns the id of the user who created the post
My post model has this relationship
# Post.php
public function user()
{
return $this->belongsTo('App\Post');
}
My user model has this relationship
# User.php
public function posts()
{
return $this->hasMany('App\Post');
}
the results that i want is that if i write
$post->user->name
it should display the user's name
Right now im getting similar results by using this statement:
{{ \App\User::find($post->user_id)->name }}
Fix your relationship definition. The Post
model should point the User
model:
use App\User; // <----
// ...
public function user()
{
return $this->belongsTo(User::class);
} // ^^^^^^^^^^^
Also, you shouldn't do queries directly from the frontend, instead, try eager loading the relationship in the back and and then return the object to the view:
public function show(Request $request)
{
$post = Post::with('user')->find(1);
// ^^^^^^^^^^^^
return view('my_view')->with('post', $post);
}
Then in your view you just use the object directly:
<h1> {{ $post->user->name }} </h1>