Friday, March 31, 2017

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');
    }
}
  @foreach($post->comments as $comment)
 // null
 
@endforeach



via flex_

Advertisement