Hello Devs,
In this tutorial, we are going to learn how to concat two column in laravel app.
Follow this set of solutions given below:
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;
}
}
I hope this example helps you.