Ad

Use REPLACE() Function With Laravel Database: Query Builder

- 1 answer

In one of my table columns I have '_' values. But I need to replace them with space. This is my code.

$crimes = DB::table('crimes')
                    ->addSelect('crime_code')
                    ->addSelect('areas.name as area')
                    ->addSelect(REPLACE('danger_level', "_", " "))
                    ->addSelect('date')
                    ->addSelect('status')
                    ->get()

But I'm getting this error,

Call to undefined function App\Http\Controllers\REPLACE()

I'm trying to use laravel Database: Query Builder and MySQL REPLACE() function. It would be great if someone can help me.

Ad

Answer

You can use selectRaw() to insert sql to your query

$crimes = DB::table('crimes')
                    ->addSelect('crime_code')
                    ->addSelect('areas.name as area')
                    ->selectRaw("REPLACE(danger_level, '_', ' ')")
                    ->addSelect('date')
                    ->addSelect('status')
                    ->get()
Ad
source: stackoverflow.com
Ad