Search code examples
laravellaravel-query-builder

How to perform TRIM() and CONCAT() in Laravel Query Builder?


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


Solution

  • $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 :)