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

wangchen's avatar

How to concatenate first_name and last_name in pluck method using the relationship

i want to fetch the concatenated name of first_name and last_name as full_name in pluck method using relationship.

public function get_contacts(Request $request){
        
        $account_id = $request->account_id;            
        $contacts = Account::find($account_id)->contacts()->get()->pluck('last_name', 'id');
        return json_encode($contacts);
}

Models Account and Contact have intermediate table for many to many relationship.I don't now how to fetch full name in pluck method.Kindly share your knowledge. Thanks in advance.

0 likes
4 replies
martinbean's avatar

@wangchen What do you mean by “contacted” full name? Do you mean concatenated full name?

You’ll probably have to map over the collection instead:

$contacts = Account::find($account_id)->contacts->maps(function ($contact) {
    return trim(sprintf('%s %s', $contact->first_name, $contact->last_name));
});
2 likes
wangchen's avatar

@martinbean yes, my typo mistake. In your above code, a singular contact argument passed to maps function, how will i get it?

$contact

wangchen's avatar
wangchen
OP
Best Answer
Level 3

I got the solution by defining an accessor in Contact model

public function getFullNameAttribute () {

    return $this->first_name.' '.$this->last_name;  

}

and getting the concatenated full name by

 public function get_contacts(Request $request){            
        $account_id = $request->account_id;            
        $contacts = Account::find($account_id)->contacts()->get()->pluck('full_name', 'id');
        
        return json_encode($contacts);
    }
1 like

Please or to participate in this conversation.