Tim Lewis
Tim Lewis

Reputation: 29278

Laravel DB::raw using SELECT column AS "Example Name"

I've come across an issue when trying to use a DB::raw query with Laravel. When I try to loop through my result set, I can't target a certain column, as it's name contains a space:

$result = DB::connection("example")->select(DB::raw(
  "SELECT table.column_1 AS 'NameOne',
  table.column_2 AS 'Name Two'
  FROM example;"
));

As you can see, NameOne doesn't contain a space, but Name Two does. When looping through the result set, I can't echo out the result of table.column_2 AS 'Name Two, as I can't target it correctly. What I've tried:

<!-- language: html -->
@foreach($result AS $item)
<tr>
  <td>{!! $result->NameOne !!}</td> <!-- Works Fine -->
  <td>{!! $result->Name Two !!}</td> <!-- Doesn't work (obvious syntax error) -->
  <td>{!! $result->Name_Two !!}</td> <!-- Doesn't work (undefined property) -->
  <td>{!! $result->Name+Two !!}</td> <!-- Doesn't work (undefined property) -->
  <td>{!! $result->NameTwo !!}</td> <!-- Doesn't work (undefined property) -->
</tr>
@endforeach

Specifically the undefined property error is:

Undefined property: stdClass::$Name_Two (View: /var/www/html/APPNAME/resources/views/index.blade.php)

I don't want to change the key as these results are being exported to Excel, and I want to preserve column names. Keeping this in mind, how would I echo out these results?

Also, the output for the dd($results):

array:1 [▼
  0 => {#179 ▼
    +"NameOne": "NameOne"
    +"Name Two": "NameTwo"
  }
]

Upvotes: 2

Views: 2690

Answers (2)

Kasyx
Kasyx

Reputation: 3200

Eloquent is returning stdClass. You can easily convert it into array with function 'get_object_vars'.

Then simply call:

{!! $result['Name Two'] !!}

Upvotes: 0

Damien Pirsy
Damien Pirsy

Reputation: 25435

You could use

<td>{!! $result->{'Name Two'} !!}</td>

Upvotes: 6

Related Questions