AR
1 year ago

Many to Many page followers efficiency?

Posted 1 year ago by AR

I am trying to make a many to many relationship but I am confused if I am doing it right. Basically a Page is owned by a user and also users can follow pages so they get updates. I created a PageFollower Model which is the link for the third table.

Here is are my tables:

users table:
id
name (string)
email (string)

pages table:
id
user_id
page title (string)
page body (string)

pages_users table:
id
user_id
page_id

And here are my models and some of the method examples in them that work fine but I am not sure if my setup is efficient or no:

// User model
class User extends Authenticatable
{

    public function pages()
    {
        return $this->hasMany(Page::class);
    }


    // to check if the user has page
    public function hasPage()
    {
        return !! $this->pages()->count();
    }

    public function followings()
    {
        return $this->hasMany(PageFollower::class);
    }

    public function follows($page)
    {
        return $this->followings->pluck('page_id')->contains($page->id);
    }

}


// Page Model
class Page extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function followers()
    {
        return $this->hasMany(PageFollower::class);
    }

    public function isFollowed()
    {
        return $this->followers()
            ->where('user_id', auth()->id())->exists();
    }

    public function follow()
    {
        if (!$this->isFollowed()) {
            return $this->followers()->create(['user_id' => auth()->id()]);
        }
    }

    public function unfollow()
    {
        $this->followers()->where('user_id', auth()->id())->delete();
    }

    public function getIsFollowedAttribute()
    {
        return $this->isFollowed();
    }

}


// PageFollower Model
class PageFollower extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function page()
    {
        return $this->belongsTo(Page::class);
    }
}

Please sign in or create an account to participate in this conversation.