Laravel Pro Tips

Laravel Pro Tips

Boosting Eloquent Efficiency: Top 3 Mistakes to Avoid

Application speed is vital for user experience. Inefficient Eloquent or database queries often cause slowdowns. This guide highlights the top three Eloquent performance mistakes and their solutions.

Laravel Pro Tips's avatar
Laravel Pro Tips
Oct 15, 2023
∙ Paid
Share

man in white dress shirt wearing black framed eyeglasses
Photo by krakenimages on Unsplash

Mistake 1: Excessive Database Queries

A frequent mistake is the N+1 query problem. It arises when multiple queries are made to the database, instead of using efficient techniques like eager loading.

Example 1: Efficiently Loading Relationships

A typical scenario might be:

In the Controller:

app/Http/Controllers/PostController.php

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

Now, assume you're using the Spatie Media Library package to fetch media files.

In your view, you might access the user and media relationships without preloading:

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 approach results in numerous database queries to retrieve associated users and media for each post.

This post is for paid subscribers

Already a paid subscriber? Sign in
© 2025 Laravel Pro Tips
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture