flex_
flex_

Reputation: 733

Laravel comments and user relationship returns null

I'm trying to implement commenting system on my website but i'm having hard time with the relationships. for some reason when i try to access the user relation from the comment class it returns null.. my code: Post.php

    class Post extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['title','created_at','username','image'];
    public function user()
    {
      return $this->belongsTo(User::class,'username');
    }
    public function votes()
    {
      //Quick note: Id refers to the post id.
      return $this->hasMany(PostVotes::class,'post_id');
    }
    public function comments()
    {
      return $this->hasMany(Comment::class,'post_id');
    }
}

User.php

class User extends Model implements Authenticatable
{
  use AuthenticableTrait;
  protected $primaryKey = 'username';
  public $incrementing = false;
  public $timestamps = false;
  protected $fillable = ['username','email','password','created_at','avatar','about'];
  // Gets avatar to display on navbar.
  public function posts()
  {
    return $this->hasMany(Post::class,'username');
  }
  public function comments()
  {
    return $this->hasMany(Comment::class,'username');  
  }
  public static function getAvatar()
  {
     return self::Where('username', '=', Session::get('username'))->value('avatar');
  }

}

Comment.php

    class Comment extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['comment','created_at','post_id','username'];
    public function user()
    {
        $this->belongsTo(User::class,'username') ;
    }
    public function post()
    {
        $this->belongsTo(Post::class,'post_id');
    }
}
public function view($post_id)
   {
      $post = Post::with('comments')->findOrFail($post_id);
      return view('posts.view',compact('post'));
   }
  @foreach($post->comments as $comment)
 // null
 {{dd($comment->user())}}
@endforeach

Upvotes: 1

Views: 641

Answers (2)

user7773364
user7773364

Reputation:

    public function displaycomment($id) {
        $data['comment'] = comment::select('comments.id', 'comments.description', 'users.name', 'comments.created_at', 'comments.post_id')->where('post_id',$id)->leftjoin('users', 'users.id', '=', 'comments.user_id')->get();
//        dd($data);
        return view('displayblog',  compact('data'));
    }

Upvotes: 0

oseintow
oseintow

Reputation: 7381

Use missed the return keyword

public function user()
{
    return $this->belongsTo(User::class,'username') ;
}

public function post()
{
    return $this->belongsTo(Post::class,'post_id');
}

Upvotes: 3

Related Questions