Search code examples
sqllaravellaravel-query-builder

Select as in laravel dummy column


I am trying to fill a select query column with dummy data with laravel query builder. The raw sql would be something like this.

SELECT CustomerName, 'Empty' as  Address
FROM Customers;

In laravel

$customers  = DB::table('customers')
    ->select(CustomerName, ''Empty' as Address')->get(); 

or

$customers  = DB::table('customers')
    ->select(CustomerName, 'Empty as Address')->get(); 

sadly does not work.


Solution

  • Laravel also offers the ->selectRaw() method for this:

    // If you have a `Customer.php` Model
    $customers = Customer::selectRaw("CustomerName, 'Empty' as 'Address'")->get();
    
    // If you don't have a `Customer.php` Model, or prefer the Builder
    $customers = DB::table('customers')->selectRaw("CustomerName, 'Empty' as 'Address'")->get();
    

    Simply omit ' around columns (like CustomerName), and you should get the expected results.