Search code examples
laraveleloquenteager-loading

Laravel Eloquent query returning non object


I am trying to reduce the number of SQL queries executed. I have a post where I want to get the author of that post and list it on the page. To reduce the number of SQL queries, I have the following code:

$posts = Post:all();
$posts->load('user');
$posts->first()->user;

I get the error/notice "Trying to get property 'user' of a non-object". How do I get rid of this error?


Solution

  • Eager loading reduces this operation to just 2 queries

    
        public function example()
        {
            $posts = Posts::with('user')->get();
    
            foreach ($posts as $post) {
                echo $post->user->name;
            }
        }