php - Adding additional column to the result of relationship in eloquent

I have two models. Both of them are pivots because they join other tables. But also they have a relationship with themselves.

class CompanyUser extends Pivot
{
    protected $table = 'company_user';

    public function companyUserProducts() {
        return $this->hasMany('App\CompanyUserProduct','company_user_id');
    }

}

class CompanyUserProduct extends Pivot
{
    protected $table = 'company_user_product';

    public function companyUser() {
        return $this->belongsTo('App\CompanyUser','company_user_id');
    }
    
}

I want to get all entities of CompanyUserProduct but with the additional column user_id from CompanyUser, so I can do pluck('user_id') on the collection and get all IDs at once. Is it possible to do it in Eloquent, or must I use Query Builder?

$companyUsers = CompanyUserProduct::with('companyUser')->get();

Answer

Solution:

You can do

$companyUsers = CompanyUserProduct::with('companyUser:id,user_id')->get();

To retrieve the CompanyUserProduct along with the id and user_id of compantUser.

Note: whatever your primary key for companyUser - make sure you select it as well. (In this case assumed to be id)

Once you retrieve the collection, the user_id will be under companyUser for each CompanyUserProduct

So, you can pluck it using dot notation.

eg:

$userIds = $companyUsers->pluck('companyUser.user_id');

Source