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

vincent15000's avatar

How to use pluck() method with custom method attribute ?

Hello,

I'd like to use pluck() with a custom method like in the example below.

In the model

public function getFullNameAttribute() { return $this->firstname." ".$this->lastname; }

In the controller

$arists = Artist::pluck("full_name", "id")->toArray();

The problem is that full_name is not a field in the table in the database.

I had a look around on the web to find a solution, but I haven't found anything.

Could you help me ?

Thanks a lot.

Vincent

0 likes
11 replies
tykus's avatar

The accessor relies on the query having already run; the data fetched and the model hydrated. You are attempting to use a PHP-land accessor in a SQL query.

You can do this, but it is not very efficient because you need to create an Artist instance for every record (even though that instance has only the needed columns:

$arists = Artist::get(['id', 'firstname', 'lastname'])
	->pluck("full_name", "id")
	->toArray();

Instead, I would let the database concatenate for me using a selectRaw query method to concatenate the fields

2 likes
MichalOravec's avatar
Level 75
$arists = Artist::selectRaw("id, concat(firstname, ' ', lastname) as full_name")->pluck('full_name', 'id');
1 like
vincent15000's avatar

Well I have tested your answer tykus. It works fine.

But I try to add an ->orderBy() after the get() method. I get an error.

MichalOravec's avatar

@vincent15000 So use selectRaw

$arists = Artist::selectRaw("id, concat(firstname, ' ', lastname) as full_name")->orderBy('full_name')->pluck('full_name', 'id')->toArray();
tykus's avatar

The get() is the end of the Query Builder part; thereafter you are in EloquentCollection land. Although many methods share the same name, you are working with different objects across that expression depending on what each method returns.

If @michaloravec answer helped you more, please consider marking it Best Reply

MichalOravec's avatar

@vincent15000 Great when you choose as best answer to your one :D

This will work propably better

$artists = DB::table('artists')->selectRaw("id, concat(firstname, ' ', lastname) as full_name")->orderBy('full_name')->pluck('full_name', 'id')->toArray();
matze13's avatar

I know this is an old thread, but since i stumpled on it while trying to find a solution, i will add my take:

If you already defined some attribute in your code you shouldn't have to do it in sql again. I would rather do

        $artists = Artist::all()->mapWithKeys(function (Artist $artist, int $key) {
            return [$key => $artist->getFullNameAttribute()];
        });
1 like

Please or to participate in this conversation.