Nyxynyx
Nyxynyx

Reputation: 63687

Strange Unhandled Exception error in Laravel

I am trying to retrieve some values from a table, but got the Unhandled exception: Trying to get property of non-object error when trying to access the results as a property of the object returned by Fluent.

Problem: Trying to access the property of the object works, even though its throwing an error. This is really puzzling to me. What may be the problem?

PHP Code

$sets = DB::table('sets')->where('user_id', '=', $user_id)->get();

// Get thumbnail of latest item added to set
foreach($sets as $set) {
    $post_set = DB::table('posts_sets')
                ->where('set_id', '=', $set->id)
                ->order_by('created_at', 'desc')
                ->first();
    print_r($post_set);  // works fine
    echo $post_set->id;  // prints out value, BUT throws the unhandled exception error!
}

Error

Unhandled Exception

Message:

Trying to get property of non-object

Location:

/home/test/public_html/application/controllers/api.php on line 47

Stack Trace:

#0 /home/test/public_html/laravel/laravel.php(40): Laravel\Error::native(8, 'Trying to get p...', '/home/test/pub...', 47)
        #1 /home/test/public_html/application/controllers/api.php(47): Laravel{closure}(8, 'Trying to get p...', '/home/test/pub...', 47, Array)
        #2 [internal function]: Api_Controller->action_sets()
        #3 /home/test/public_html/laravel/routing/controller.php(323): call_user_func_array(Array, Array)
        #4 /home/test/public_html/laravel/routing/controller.php(283): Laravel\Routing\Controller->response('sets', Array)
        #5 /home/test/public_html/laravel/routing/controller.php(165): Laravel\Routing\Controller->execute('sets', Array)
        #6 /home/test/public_html/laravel/routing/route.php(153): Laravel\Routing\Controller::call('api@(:1)', Array)
        #7 /home/test/public_html/laravel/routing/route.php(124): Laravel\Routing\Route->response()
        #8 /home/test/public_html/laravel/laravel.php(125): Laravel\Routing\Route->call()
        #9 /home/test/public_html/public/index.php(34): require('/home/test/pub...')
        #10 {main}

Upvotes: 0

Views: 3322

Answers (2)

Gabriel Koerich
Gabriel Koerich

Reputation: 587

You should use eloquent to do that.

Remember that you are doing a query inside a foreach, you'll have performance problems when your database gets big.

Using eloquent you can just use eager loading like this:

$sets = Set::with('posts')->where_user_id($user_id)->get();

foreach($sets as $set)
{
var_dump($set);
var_dump($set->posts);
}

You can see more in http://laravel.com/docs/database/eloquent

Upvotes: 0

crynobone
crynobone

Reputation: 1814

First of all, $post_set query would return NULL if no data record available from database, which mean you should always first check for is_null($post_set).

Upvotes: 2

Related Questions