The error is like below:
Trying to get property of non-object (View: C:\xampp\htdocs\laravel\app\views\singlePost.blade.php)
There is 2 tables: Comments and Users. In comments table there is a column named user_id and that refers to id column that is in users table. And there is username column in the users table. This is how I try to print username.
@foreach($theComments as $theComment)
<div>{{$theComment->users->username}}</div>
<div style="border:1px solid black;margin:8px 0px 8px 0px">{{$theComment['content']}}</div>
@endforeach
and controller:
public function singlePost(Posts $post)
{
$id = $post['id'];
$comments = Comments::where('post_id','=',$id)->get();
$users = Users::all();
return View::make('singlePost')->with('thePost', $post)->with('theComments', $comments)->with('theUser', $users);
}
and /Model/Comments.php
<?php
class Comments extends Eloquent{
protected $fillable = array('user_id');
public function users(){
return $this->belongsTo('Users');
}
}
What's the problem and how can i solve it?
First I suggest you rename the relationship to just user()
(At the beginning thought it would return a collection). The source of the error is probably a comment that has no user assigned.
The best way would just be to exclude those from your query. You can use has()
for that
$comments = Comments::has('user')->where('post_id','=',$id)->get();
And you should also eager load the user relationship, otherwise you have a n+1 queries issue:
$comments = Comments::has('user')->with('user')->where('post_id','=',$id)->get();
Try wrapping this if around it in your view:
@foreach($theComments as $theComment)
@if($user = $theComment->users)
<div>{{$user->username}}</div>
@endif
@endforeach
You need to load the relationship first
$comments = Comments::with('users')->where('post_id','=',$id)->get();