dspitzle
dspitzle

Reputation: 770

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

So 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

Answers (1)

apokryfos
apokryfos

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

Related Questions