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

Alex303's avatar

Pluck distant relation

I have the User model which is related to a Job model (jobs table has 'user_id' column) and the Job model related to JobFunction model through a pivot table 'job_job_function'.

I'd like to pluck id's of all JobFunctions that a user has through the Job model.

Have tried this in Tinker which returns "all: [ null, null, ]" User::find(5)->jobs()->get()->pluck('jobFunctions.id')

It returns 2 null in the array because this user has 2 jobs.

0 likes
2 replies
LaryAI's avatar
Level 58

To pluck the ids of all JobFunctions that a user has through the Job model, you can use the pluck method on the jobFunctions relationship of the Job model. Here's an example:

$user = User::find(5);
$jobFunctionIds = $user->jobs()->with('jobFunctions')->get()->pluck('jobFunctions.*.id')->flatten()->unique();

In this example, we first retrieve the user with ID 5. Then, we eager load the jobFunctions relationship on the jobs relationship. We use the pluck method to extract the id attribute from each jobFunction model. The * wildcard is used to indicate that we want to pluck the id attribute from all jobFunction models. Finally, we use the flatten and unique methods to remove any duplicates and return a collection of unique job function IDs.

Note that this solution assumes that the Job model has a jobFunctions relationship defined like this:

class Job extends Model
{
    public function jobFunctions()
    {
        return $this->belongsToMany(JobFunction::class);
    }
}
Alex303's avatar

Thanks, I had to use 'jobFunctions.*.id' instead of 'jobFunctions.id'

Please or to participate in this conversation.