Reputation: 51
I m new to laravel i want to display all the posts on a view with the name of the user who created the post.. I m trying to do that but I m getting the error of "Trying to get property 'name' of non-object " .. Any kind of help will be appreciated Thank you
User.php
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function Posts(){
return $this->hasMany('\App\Post');
}
protected $fillable = [
'name', 'email', 'password','verifyToken','dob',
];
Post.php
class Post extends Model
{
public function Users(){
return $this->belongsTo('\App\User');
}
protected $fillable = [
'title','body','thumbnail','user_id',
];
PostController.php
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts=Post::paginate(5);
return view('\home2',compact('posts'));
}
web.php
Route::get('/home2', 'PostController@index')->name('home');
Home2.blade.php
@foreach($posts as $post)
<div class="text-center">
<h1 align="center">{{$post->title }}</h1>
<h4 align="center">{{$post->body}}</h4>
<p>{{ $post->created_at->diffForHumans() }}</p>
<p> {{$post->Users->name}}</p>
Upvotes: 0
Views: 90
Reputation: 1441
Your models should look like this.
User.php
public function posts(){
return $this->hasMany('App\Post');
}
Post.php
public function user(){
return $this->belongsTo('App\User','user_id');
}
then your blade code should be like this,
<p> {{$post->user->name}}</p>
Upvotes: 1
Reputation: 7420
Eager load the users:
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts=Post::with('users')->paginate(5);
return view('\home2',compact('posts'));
}
Then on the blade:
<p> {{$post->user->name}}</p>
Update your relationship classes from:
public function Posts(){
return $this->hasMany('\App\Post');
}
to
public function posts(){
return $this->hasMany(Post::class);
}
Import at the top use App\Post;
and
public function user(){
return $this->belongsTo(User::class);
}
Import at the top use App\User;
Upvotes: 1