Taylor
Taylor

Reputation: 3141

Laravel - Repetitive query in blade view - Reducing number of queries

I am in a situation where I have a lot of relationships and it is becoming a problem as it slows down a site when I do a lot of queries.

For instance, I am doing a foreach loop for all blogs and getting the user who made the blog.

@foreach ($blogs as $blog)
    <a href="{{ route('blog.view', str_slug($blog->title)) }}">{{ $blog->title }}</a>

    {{ $blog->created_at }}

    <a href="{{ viewProfile($blog->user) }}"><{{ $blog->user->username }}/a>

    Last Commenter:
    <a href="{{ viewProfile($blog->lastCommenter()->user) }}">
        {{ $blog->lastCommenter()->user->username }}
    </a>

@endforeach

That alone is more than 50+ queries.. And if there are like 100 blogs, the number of queries is way off.

How can I avoid doing this? I have stored it in a variable in this view but I don't want to really put any PHP code in a blade file. How can I avoid doing this? I have tried using cache in database but that's also doing a few queries to the cache table in database. I am also using eager loading which has helped a lot. But how can I best do this kind of things?

Thank you very much for your response in advance.

Upvotes: 2

Views: 1021

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

That is called N+1 problem. You should learn how to use Eager loading and load relations first. Then iterate over collection to display data to the user.

An example of eager loading of multiple relations from documentation:

$books = App\Book::with('author', 'publisher')->get();

An example and tutorial suggested by @Achraf Khouadja:

$blogs = blog::with('lastCommenter', 'user')->get();

Upvotes: 5

Related Questions