CONCAT Two Columns in Laravel with Example
In this article, I’ll share three methods to CONCAT two columns in Laravel. Let’s see the methods:
Table of Contents
Step 1 : Wrap Query in DB::raw
We need to wrap the query in DB::raw
. Here’s the example:
public function users()
{
$users = DB::table('users')->select("*", DB::raw("CONCAT(users.first_name,' ',users.last_name) AS full_name"))
->get();
foreach ($users as $user) {
echo $user->full_name . '<br>';
}
}
Step 2 : Using Pluck Method
We can use the pluck()
method to concat two columns like this:
public function users()
{
$users = DB::table('users')->select('id', DB::raw("CONCAT(users.first_name,' ',users.last_name) AS full_name"))->get()->pluck('full_name', 'id');
dd($users);
}
Step 3 : Define Custom Method in Model
At first, we need to add a function in the User model. Open the User modal from app folder. We are going to create a method called getFullNameAttribute
. The postfix ‘Attribute‘ is needed for the function name.
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'password',
];
/**
* Get the user's full name.
*
* @return string
*/
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
Now just run the query and get full name like this:
public function users()
{
$users = User::get();
foreach ($users as $user) {
echo $user->full_name . '<br>';
}
}
The tutorial is over. Thanks for reading. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)