thewoodcutter
1 year ago

ManyToMany not gathering multiple pivot entries

Posted 1 year ago by thewoodcutter

Hi I've been struggling for days now with a many to many relationship where I have profiles and users models. I want to get all the followed profiles that a user is related to (multiple) so I can further deal with the data and I keep getting only one profile when there are two or more in my test situation. Please help?

Here is my User model:

public function profile() {
    return $this->hasOne('\App\Profile');
}

public function followers()
{
    return $this->belongsToMany(Profile::class, 'followers', 'leader_id', 'follower_id')->withTimestamps();
}

Here is my profiles model:

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

public function followed()
{
    return $this->belongsToMany(User::class, 'followers', 'follower_id', 'leader_id')->withTimestamps();
}

This is my pivot table for this purpose:

public function up()
{
    Schema::create('followers', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('follower_id')->unsigned();
        $table->integer('leader_id')->unsigned();
        $table->timestamps();

        $table->foreign('follower_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('leader_id')->references('id')->on('profiles')->onDelete('cascade');
    });
}

And in my controller where I am trying to get the multiple profiles only related to the user having followed those profiles:

public function getFaves($dreamer) {
    $user = Auth::user();
    $following = $user->followers()->get();

    dd($user,$following);
    return view('user.dreamer.faves');
}

The output from this gives me only one collection instance of the profile, the first one. I am not too experienced in programming or working with arrays.

I am curious if there's a simple mistake, or if there's not supposed to be this many relationships with the same two models as I also have a one to one relationship from a profile belonging to a user. I am at a complete loss please advise me what to do.

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