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.
app/User.php
/**
* 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.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.