How To Concat Two Columns In Laravel?

Laravel 6 , Laravel , Laravel 7

Nicesnippets

41887

02-06-2020


Hello Friends,

In this blog, I will share you how to concat two column in laravel app. I will show two column in merge method. we are two column concat using three method.

If you need to concat two columns with laravel query builder then i will give you example of how to concat two columns in laravel application.

I will give you three way solution for concatenate columns in laravel. both way you can easily concatenating two columns in laravel application.

First way is we will concat two columns in select statement using db raw in laravel.Second way is we will concat two columns in select statement using pluck in laravel. Third one is model in use custom method to concat two column.

Solution 1 : Using DB::Raw


public function users()

{

$users = DB::table('users')->select("*", DB::raw("CONCAT(users.first_name,' ',users.last_name) AS full_name"))

->get();

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

}

Solution 2 : Using Pluck method

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');

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

}

Solution 3 : Create method in Model

app/User.php

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

class User extends Authenticatable

{

/**

* 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 getFullName()

{

return "{$this->first_name} {$this->last_name}";

}

public function users()

{

$users = User::get();

foreach ($users as $key => $value) {

echo $value->getFullName;

}

}

It will help you...


Recommended Posts