CONCAT Two Columns in Laravel with Example

Last modified on December 12, 2019 56 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

In this article, I’ll share three methods to CONCAT two columns in Laravel. Let’s see the methods:

Table of Contents

  1. Wrap Query in DB::raw
  2. Using Pluck Method
  3. Define Custom Method in Model

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. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *