Reputation: 29278
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
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