Laravel follower / following relationship

I'm trying to create a simple sequential / next system in laravel, nothing special, just click a button to follow or unsubscribe, and display followers or people following you.

My problem is that I cannot figure out how to establish relationships between models.

These are migrations:

-User migration:

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('email');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('password');
        $table->string('gender');
        $table->date('dob');
        $table->rememberToken();
    });

-Migration module:

Schema::create('followers', function (Blueprint $table) {

        $table->increments('id');
        $table->integer('follower_id')->unsigned();
        $table->integer('following_id')->unsigned();
        $table->timestamps();        
    });
}

And here are the models:

-User model:

   class User extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;
    public function posts()
    {
        return $this->hasMany('App\Post');
    }

    public function followers()
    {
        return $this->hasMany('App\Followers');
    }

}

- And the followers model is mostly empty, that's where I got stuck

I tried something like this:

class Followers extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

but it didn’t work.

Also, I would like to ask if you can tell me how to write the "follow" and "display followers / follow" functions. I read every tutorial I could find, but not using. I don't seem to understand.

+4
2

, "" App\User. App\User :

// users that are followed by this user
public function following() {
    return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
}

// users that follow this user
public function followers() {
    return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
}

$a $b:

$a->following()->attach($b);

$a $b:

$a->following()->detach($b);

$a:

$a_followers = $a->followers()->get();
+7

, ?

0

Source: https://habr.com/ru/post/1680751/


All Articles