1

I'm trying to get the usernames of the users who have posted comments, however, I keep getting "Trying to get property 'username' of non-object" error. I believe my relationships are done correctly but I might be wrong.

My tables:

Table: Users
Columns: id, username, password

Table: Comments
Columns: id, user_id, image_id, comment

Comment model:

class Comment extends Model
{
    public function users(){
        return $this->belongsTo('App\User');
    }
}

User model:

class User extends Model implements Authenticatable
{
    public function comments(){
        return $this->hasMany('App\Comment');
    }
}

I'm getting the comments like this:

$comments = Comment::with('users')->where('image_id', $id)->get();

And then trying to loop through them in the view like this:

@foreach($comments as $comment)
    <p>{{ $comment->comment }}</p>
    <p>{{ $comment->users->username }}</p>
@endforeach

And when I dd($comments), I see:

 #relations: array:1 [▼
        "users" => null
 ]

I'm not sure why is it null though.

Onyx
  • 5,186
  • 8
  • 39
  • 86
  • 3
    Why? Because `$comment->users` is not an object – Phil Dec 18 '18 at 23:03
  • As far as I understand, I could do that based on https://stackoverflow.com/questions/29165410/how-to-join-three-table-by-laravel-eloquent-model?noredirect=1&lq=1 . – Onyx Dec 18 '18 at 23:09
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – miken32 Dec 19 '18 at 00:10
  • Your relations is correct. maybe you db is not correct. Check comments table user_id column is null or not??4 – Davit Zeynalyan Dec 19 '18 at 06:11

3 Answers3

1

Try this

@foreach($comments as $comment)
    <p>{{ $comment->comment }}</p>
    <p>{{ !empty($comment->users->username) ? $comment->users->username : '' }}</p>
@endforeach

Also I suggest you change you relations name users to user

class Comment extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }
}

Get comments

$comments = Comment::with('user')->where('image_id', $id)->get();

And in view

@foreach($comments as $comment)
    <p>{{ $comment->comment }}</p>
    @if(!empty($comment->user))
        <p>{{ $comment->user->username }}</p>
    @endif
@endforeach
Davit Zeynalyan
  • 8,418
  • 5
  • 30
  • 55
1

try this way :

@foreach($comments as $comment)
    <p>{{ $comment->comment }}</p>
    <p>{{ $comment->users["username"] }}</p>
@endforeach
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
0
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ optional($comment->users)->username}}</p> 
@endforeach

Try this approach.