CONCAT Two Columns in Laravel with Example

  4523 views   1 year ago Laravel

When working with Laravel query, you may want to get two column values to single column. This is helpful where you need full name of user combining first name and last name.

This can be done through MySQL CONCAT method as well as Laravel accessors. We will use both ways to group two column into single column.

CONCAT method

Laravel provides DB::raw() method to inject MySQL query into database. you can use MySQL CONCAT method to combine two columns into single virtual column. Here is the below example.

 * return users details.
 * @param  void
 * @return \Illuminate\Http\Response
public function index()
    $users = DB::table('users')
            \DB::raw("CONCAT(users.first_name,' ',users.last_name) AS full_name")

    return view('users',compact('users'));

And in the blade template, you can access full_name property.

@foreach ($users as $user)
    {{ $user->full_name }}

Laravel accessors

An accessor converts an model data when it is accessed. To create accessor, you can create get{Attribute}Attribute method on your model into studly cased name of the column you wish to access.

For the above method, if you want to receive full_name from first_name and last_name column, first create method in User model.


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
     * Get full name.
     * @return string
    public function getFullNameAttribute()
        return "{$this->first_name} {$this->last_name}";

Now you will have full_name virtual column whenever you use model to fetch data from the database. You can use it same as first one way.

There is also one simple PHP way you can use string concatenation full name. But you have to use concatenation everytime when you have to get full name which is not DRY(Don't Repeat Yourself) code way.

@foreach ($users as $user)
        $full_name = $user->first_name. " " .$user->last_name;
    {{ $full_name }}

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]