Pionas
Pionas

Reputation: 346

Laravel5.1 eloquent slow action

i add few Model and one Controller.

Controller

Forum:

public function showCategory($alias)
{
    $page_title = trans('forum.forum').' :: '.trans('static.website_title');

    $category_info = ForumCategory::where('category_alias', $alias)->first();

    return view('layout.pages.forum.category', compact('category_info'));
}

Models

ForumCategory

public function threads()
{
    return $this->hasMany('App\Forum\ForumThread', 'category_id');
}

ForumThread

public function posts()
{
    return $this->hasMany('App\Forum\ForumPost', 'thread_id');
}

category.blade.php:

@extends('layout.default')

@section('content')

{{ $category_info->category_alias }}

{{--*/ $ThreadList = $category_info->threads()->paginate(20) /*--}}

    @foreach( $ThreadList as $thread )
    {{--*/ $a = $thread->posts->count() /*--}}
        <a href="{{URL::to('/forum', array($category_info->category_alias, $thread->thread_alias))}}">{{ $thread->thread_id }} - {{ $thread->thread_subject }} - {{ $a }}</a><br /><br />
    @endforeach
@stop

Page rendering time is: ~0.701548814774 seconds. In my opinion i think is very slow... How I can speed this?

Upvotes: 0

Views: 91

Answers (1)

Francesco Malatesta
Francesco Malatesta

Reputation: 679

I am assuming you want to execute all the code you specified in the example, including commented lines. I think that what you're searching is Eager Loading.

It can be easily used to avoid the N + 1 queries problem and improve performances.

You should use something like:

ForumCategory::with('threads')->where('category_alias', $alias)->first();

Also, you can specify nested relationships.

ForumCategory::with('threads.posts')->where('category_alias', $alias)->first();

More details here! The documentation example is really easy to understand!

Also, it would be useful to profile your application requests using a profiler. There are many out there, barryvdh/laravel-debugbar is one of these.

Upvotes: 1

Related Questions