Boubou
4 months ago
413
3
Laravel

"Favorites" relationship - I am stuck

Posted 4 months ago by Boubou

Hi all,

I would like to create a "Favorite Posts" table but I am unsure about the relationship itself. At the moment I have created a table as "post_user":

           $table->integer('user_id');
            $table->integer('post_id');

I wanted to create a model called "Favorite" and set it as the table "post_user" but if I understand correctly, the relationships should be set inside the USER and POST models and not in the FAVORITE model.

ie: USER Model:

    public function posts()
    {

        return $this->belongsToMany(Product::class, 'post_id');
    }

POST Model

    public function users()
    {

        return $this->belongsToMany(User::class, 'user_id');
    }

How will Laravel pickup the post_user table automatically when I wish to have all the post of favorite posts of the current user? Does it do it automatically because of the naming convention? Or do I need the "FAVORITE" model?

Thank you

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