Skip to content
Eloquent optimizationIntermediate5 questions

Eloquent query performance

N+1 queries, counting, plucking and chunking: pick the option that does less work.

  1. 01This loop runs one query for the posts and then one more query per post. Which change fixes that?
    $posts = Post::all();
    
    foreach ($posts as $post) {
        echo $post->author->name;
    }
  2. 02You only need the number of posts a user has. Which line avoids loading every post into memory?
  3. 03You need a list of every user's email address and nothing else. Which is the most efficient?
  4. 04This job should deactivate every active user, but it skips some of them. What is the documented fix?
    User::where('active', true)->chunk(100, function ($users) {
        foreach ($users as $user) {
            $user->update(['active' => false]);
        }
    });
  5. 05After Post::withCount('comments')->get(), where is each post's number of comments?

Answers are scored on the server. Unanswered questions count as incorrect.

laravel.now is an independent community project. It is not affiliated with, endorsed by, sponsored by, or in any way officially connected to Laravel, Laravel LLC, Taylor Otwell, or the Laravel framework maintainers. Laravel is a trademark of Taylor Otwell. All other trademarks belong to their respective owners.

This site is operated by the makers of Lockhound. Links to Lockhound are promotional.