laravel-blog icon indicating copy to clipboard operation
laravel-blog copied to clipboard

Lazy Loading issues across the package

Open Preshiousy1 opened this issue 2 years ago • 2 comments

There are a number of lazy loading issues across the package that start to arise once I have added more than one post, you are calling model relationships within views which is not ideal, it should be called with a YourModel::with('relation')->get() before passing into the view. I know I could turn off lazy loading but that is not ideal for performance.

An example is line 58 of your NinshopsAdmin Controller. looks like this: $posts = BinshopsPostTranslation::orderBy("post_id", "desc")->where('lang_id', $language_id) ->paginate(10);

should be this:

$posts = BinshopsPostTranslation::with(['post'])->orderBy("post_id", "desc")->where('lang_id', $language_id) ->paginate(10);

as you are calling $post->post->name in the view, there are a number of other instances as well.

Screenshot 2022-07-15 at 15 07 17

Preshiousy1 avatar Jul 15 '22 14:07 Preshiousy1

@Preshiousy1 thanks for your suggestion, yes it causes N+1 query problem. It comes from the translation structure, may be we need a refactor, or going back to the single language to keep the package structure simple, because the current multi lang structure make package structure a little complex.

Anyway, thanks for your constructive report.

samberrry avatar Dec 28 '22 12:12 samberrry

I tried to monitor queries using this tool: https://github.com/supliu/laravel-query-monitor

experiments: 1- call for http://127.0.0.1:8000/blog -> 10 queries used - > 1 post 2- call for http://127.0.0.1:8000/blog -> 12 queries used - > 2 posts

experiment 1: https://user-images.githubusercontent.com/20775532/209834122-6885477d-e2aa-492f-a295-e6cafabe3c5c.mp4

experiment 2:

https://user-images.githubusercontent.com/20775532/209835383-0ac65553-1794-4a33-b2ef-563900b3a211.mp4

samberrry avatar Dec 28 '22 15:12 samberrry