2

I tried to take FirstName, middlename, Lastname used the Query Builder in combination with RAW but failed. is my way wrong? Thanks

$student = \DB::table('student')
                        ->select(DB::raw('RTRIM(LTRIM(CONCAT(
                                          COALESCE(FirstName +  ''),
                                        COALESCE(MiddleName +  ''),
                                        COALESCE(Lastname, ''))))
                                        AS Name'))
                        ->get();

2
  • COALESCE(FirstName + '') doesn't appear valid Mar 23, 2019 at 23:04
  • Is there a reason you're not using Eloquent models?
    – ceejayoz
    Mar 24, 2019 at 1:10

5 Answers 5

3
$student = DB::table('student')
    ->select(
        DB::raw("TRIM(CONCAT(FirstName,' ',MiddleName,' ',LastName)) AS Name")
    )->get();

TRIM Function - Remove leading and trailing spaces from a string See examples and how to use it

CONCAT Function - Add several strings together using comma: See examples and how to use it

Hope will help you :)

3

Why not using Laravel model way of achiving this?

class Student extends Model {

     protected $appends = 'full_name';

     public function getFullNameAttribute() {
         return $this->FirstName . ' ' . $this->MiddleName . ' ' . $this->LastName; 
     }
}

Then, Student::get() will have full_name attribute for each student.

2
  • Well, you could use Eloquent for this, but they aren't. So I'm not sure it's really an answer to use an ORM over the query builder. Mar 23, 2019 at 23:12
  • @Devon It's a perfectly good answer barring an "I can't use Eloquent for <good reason>" from OP.
    – ceejayoz
    Mar 24, 2019 at 1:10
1

The + symbols should be a comma:

$student = \DB::table('student')
    ->selectRaw("TRIM(CONCAT(COALESCE(FirstName,  ''), COALESCE(MiddleName,  ''), COALESCE(Lastname, ''))) AS Name")
    ->get();
0

Try this :

$student = \DB::table('student')
               ->select(\DB::raw('CONCAT_WS(" ", `FirstName`, `MiddleName`, `Lastname`) as Name'))
               ->get();
0

Try this :

$student = Student::select(\DB::raw('CONCAT_WS(" ", `FirstName`, `MiddleName`, `Lastname`) as Name'))
               ->get();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.