dspitzle dspitzle - 2 years ago 93
PHP Question

Laravel Query Builder result object is throwing "Trying to get property of non-object" exception

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

, which has an

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`=?
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:

  • For the family I'm working with,
    resolves to

    Array ( [0] => stdClass Object ( [name_list] => Esper-Smith/Smith ) )

  • print_r($names[0])
    resolves to

    stdClass Object ( [name_list] => Esper-Smith/Smith )

  • print_r($names[0]->name_list)
    resolves to

  • print_r(is_object($names[0]))
    returns 1

So why am I getting an Exception that
is a non-object? Why is an Exception being thrown for an expression that can successfully be resolved by a
call? I don't like it when my code starts getting cute...

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download