Top Menu

The performance of our applications is one of the top things we should care about. Inefficient Eloquent or DB queries are probably no.1 reason for bad performance. In this tutorial, I will show you the top mistakes developers make when it comes to Eloquent performance, and how to fix them.

In this blog post, we will discuss some strategies to help you avoid this mistake and improve your application’s performance.

Mistake : Too Many DB Queries

  1. Use Eager Loading

One of the main benefits of using an ORM like Eloquent is that it allows you to work with your database using object-oriented syntax. However, if you’re not careful, this can lead to what is known as the “N+1 query”. This occurs when you retrieve a collection of objects and then loop through each one, retrieving related objects for each item. This can result in a large number of queries being executed against the database.

To avoid this, you can use eager loading. Eager loading allows you to retrieve related objects along with the initial query, reducing the number of queries executed. For example, instead of retrieving a collection of posts and then looping through each one to retrieve the author of each post, you can use eager loading to retrieve both the posts and their authors in a single query.

Example 1: Eager Load Relationship

One of the most common example looks like this:

app/Http/Controllers/PostController.php

public function index()
{
    $posts = Post::all();
 
    return view('posts.index', compact('posts'));
}

In the Blade file, you would use user and media relationships directly without preloading them:

resources/views/posts/index.blade.php

<ul>
    @foreach($posts as $post)
        <li>
            {{ $post->title }} / By {{ $post->user->name }}
            @foreach($post->getMedia() as $media)
                {{ $media->getUrl() }}
            @endforeach
        </li>
    @endforeach
</ul>

This produces a result similar to this, which contains a lot of database calls to get related users and media for a post:

To fix this, we can simply modify the controller to eager load the relationship like so:

  • Change all() to get()
  • Add the with(['user', 'media']) method to load the relationships

app/Http/Controllers/PostController.php

public function index()
{
    $posts = Post::with(['user', 'media'])->get();
 
    return view('posts.index', compact('posts'));
}

As a result, you will see only 3 queries being executed to load all the required data for the view:

About The Author

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Close