Reputation: 770
This is one of those headscratchers where the error message is directly contradicted by the evidence on hand. I have the following method in a Laravel model called Family
, which has an id
field:
public function getFamilyName()
{
$search_id = ( empty( $this->primary_id ) ) ? $this->id : $this->primary_id;
$names = DB::select(
'SELECT GROUP_CONCAT(`last_name` ORDER BY `last_name` SEPARATOR \'/\' ) `name_list`
FROM (SELECT `last_name`
FROM `children`
WHERE `primary_id` IS NULL
AND `family_id`=?
UNION
SELECT `last_name`
FROM `parents`
WHERE `primary_id` IS NULL
AND `family_id`=?) `last_names`',
array($search_id, $search_id) );
$nameList = $names[0]->name_list;
return ($nameList=="") ? 'Unnamed': $nameList;
}
This code has worked fine until earlier today, but is now throwing a Trying to get property of non-object exception at
$nameList = $names[0]->name_list
.
I hadn't touched the method, so I'm at a loss as to what's gone wrong. I've done some quick and dirty investigation via thrown Exceptions using print_r, and determined the following:
print_r($names)
resolves toArray ( [0] => stdClass Object ( [name_list] => Esper-Smith/Smith ) )
print_r($names[0])
resolves tostdClass Object ( [name_list] => Esper-Smith/Smith )
print_r($names[0]->name_list)
resolves to 'Esper-Smith/Smith'
print_r(is_object($names[0]))
returns 1So why am I getting an Exception that $names[0]
is a non-object? Why is an Exception being thrown for an expression that can successfully be resolved by a print_r()
call? I don't like it when my code starts getting cute...
Upvotes: 0
Views: 108
Reputation: 40653
As DB::Select wraps around PDO
and makes use of the fetchMode
property to choose between object or array, you need to ensure that your fetchMode
is properly set before executing your queries.
The Laravel Connection
implements method setFetchMode
which sets the default connection mode. This change will persist for all the remainder of the script execution so if you change it somewhere you need to remember to change it back to how the rest of your code expects it to be.
Upvotes: 1