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

RafaelMunoznl's avatar

Eloquent WHEN: Add attributes to the query results depending on column value

I have a following query to select a client with its title ('Dr.' , 'Prof.', etc).

I have a title_idcolumn and all the possible titles in an array under config/titles.php

Titles.php

<?php

return [
    'titles' => [
        '1' => 'Dr.',
        '2' => 'Prof.',
    ]
];

In my query I want to achieve that IF title_id = 1 then add an attribute as title = 'Dr.' If it is 2 then 'Prof.' and so on. I want to do it in the query instead looping outside the results.

Client::select('clients.id as client_id', 'clients.firstname', 'clients.lastname')
		->when('clients.title_id' == 1, function ($query) {
			return $query->select('clients.title_id as title = `Dr.`'); })
		->when('clients.title_id' == 2, function ($query) {
			return $query->select('clients.title_id as title = `Prof.`'); })
		->first();

However, it ignores the title_id. It does not give back error. It just ignores the title_id

What am I doing wrong?

0 likes
5 replies
Snapey's avatar

whenis not for this - it is for including additional query statements when (for example) the request includes some value. not for checking table data.

Use an accessor, or Caleb Porzio's Sushi

Sushi allows you to create an eloquent model with static data. you can then have it as a relation.

But why not just store this piece of text directly on the clients table?

RafaelMunoznl's avatar

@snapey the data directly in the database could lead to different written items or misspellings like 'Professor' , 'Prof.', 'Prof' (without end dot) for the same concept.

As I need to translate the result, the string muss be the same one always.

Until now I have just create a model a controllers and a relatuon, allowing CRUD, but in this case that would be to much

MichalOravec's avatar
Level 75

@rafaelmunoznl In mysql it could be like this

Client::selectRaw('clients.id as client_id, IF(clients.title_id = 1, "Dr.", "Prof.") as title, clients.firstname, clients.lastname')->first();

Also if you select only from one table you dont' have to use clients.id as client_id but just id as client_id and so on.

RafaelMunoznl's avatar

@michaloravec. I trying to use as much as possible thepossibilities of MySql to avoid endless looping afterwards.

Thanks a lot

Snapey's avatar

Just like to point out that your list of selections can come from a database table, used in the form as a select and then dropped as a string into the user record.

No need to have a permanent relationship to another table - just use it for the initial filling of the field.

Please or to participate in this conversation.