How to Concat two columns in Laravel

  2 weeks ago     Views:  106  


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')
        ->select(
            "users.*",
            \DB::raw("CONCAT(users.first_name,' ',users.last_name) AS full_name")
        )
        ->get();

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

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

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

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.

<?php

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)
    @php
        $full_name = $user->first_name. " " .$user->last_name;
    @endphp
    {{ $full_name }}
@endforeach

Happy coding...


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments