samedi 16 janvier 2016

Polymorphic relation in laravel for following a user

I've a User model and a likes table. I applied polymorphic relation to it.

likes table has the following structure:

user_id --- likeable_id ---- likeable_type
eg: 1 ---- 5 ---- App\User  //This indicates user 1 follows 5
eg: 3 ---- 1 ---- App\User  //This indicates user 3 follows 1

Now I'm trying to get the followers and following list.

In the User model I added

 public function likes()
  {
        return $this->morphMany(Like::class, 'likeable');
  }

    public function followers()
    {
        return $this->belongsTo('App\Like', 'likeable_id', 'user_id');
    }

and from the controller, I've tried to do this:

$user1 = User::with('followers')->where('username', $username)->first();

But it's returning null for the followers relation. Am I doing it right?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire