CONCAT columns with Laravel 5 eloquent


Consider me as laravel beginner

The goal is: I have two colums, now I need the id to be prefixed with the component name of same row in the table.

For Example (Working)… I have Mysql like

FROM   `components` 

And output is


|TestComp 40  |
|component 41 |
|test 42      |

I need the same in laravel eloquent way, as here Component is Model name. So i tried something like

$comp=Component::select("CONCAT('name','id') AS ID")->get()

but it doesn’t work.
I think because the syntax is wrong.
Kindly help me with the correct syntax. Using laravel Models.

Note: I made the above query, referring this as which available on internet.

User::select(DB::raw('CONCAT(last_name, first_name) AS full_name'))


You need to wrap your query in DB::raw:

$comp = Component::select(DB::raw("CONCAT('name','id') AS ID"))->get()

Also, note because you are doing your query like this, your model might behave differently, because this select removes all other fields from the select statement.
So you can’t read the other fields from your model without a new query. So ONLY use this for READING data and not MODIFYING data.

Also, to make it in a nice list, I suggest you modify your query to:

$comp = Component::select(DB::raw("CONCAT('name','id') AS display_name"),'id')->get()->pluck('display_name','id');
// dump output to see how it looks.
dd($comp);// array key should be the arrray index, the value the concatted value.

Answered By – Tschallacka

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published