Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

brianbola90's avatar

BelongToMany With Pivot

Hi I hope this makes sense. What i want to do is gather a list of users whose role is guest i.e. has a role id of 3. Ive created a ManytoMany relationship between users and weddings tables and the pivot table includes the role_id column. I cant seem to be able to return a list of users names no matter what I do! Can some help? Below is what I have done so far.

Wedding Model

public function accounts()
    {
        return $this->belongsToMany(Account::class, 'account_weddings', 'wedding_id', 'account_id')->withPivot('role_id');
    }

Account Model

 public function weddings()
    {
        return $this->belongsToMany(Wedding::class, 'account_weddings', 'account_id', 'wedding_id')->withPivot('role_id');
    }

Wedding Repository

 public function __construct($model = null)
    {
        $this->model = $model ?: new Wedding;
    }

public function retrieveGuestList()

    {
        $this->model = $this->model->accounts()->where('role_id' , '3')->get();

        return $this;

    }

Wedding controller

  
    public function guestlist()
    {
        $wedding = new WeddingRepository();
        return view()->make('wedding.guestlist')->with('weddings', $wedding->retrieveGuestList());
    }
0 likes
2 replies
bobbybouwmann's avatar

Well you return a new Wedding, since you don't pass any model to the constructor of your repository. This means that you work with a new Wedding model. So this model is not associated with anything since it's not even saved in the database.

mrLilly's avatar

Instead of using where, in the retrieveGuestList() method, use wherePivot(). You would also need to look up the wedding first, or add a method to find a wedding as you are currently using a new wedding model which will have no relationships.

/**
 * Find a model by id
 *
 * @param integer $id
*/
public function getById($id)
{
    return $this->model->findOrFail($id);
}

/**
 * Retrieve a collection of guests for a given wedding
 *
 * @param integer $id
 * @return Illuminate\Database\Eloquent\Collection a collection of Account models
*/
public function retrieveGuestList($id)
{
    $model = $this->getById($id);
    return $model->accounts()->wherePivot('role_id' , '3')->get();
}

In your controller

...
$wedding = new WeddingRepository();
$guestsCollection = $wedding->retrieveGuestList();
...

I would rename the 'wedding' variable that is being passed to the the view for clarity.

public function guestlist()
{
    $wedding = new WeddingRepository();
    // Pass the id of the wedding to the retrieveGuestList method.
    $guestsCollection = $wedding->retrieveGuestList(1);
    return view()->make('wedding.guestlist')->with('guestlist', $guestsCollection);
}

Please or to participate in this conversation.