Laravel View Composer duplicating SQL queries for every view bind. How it runs once?
Why does this happen?
Illuminate\View\View::renderContents() the method is responsible for calling the composer bound to a view, and since any form of view rendering (Blade template inheritance or simple
@include statements) executes that method, it means that when any view is rendered any composer bound to it gets triggered.
Since in case when using a
* wildcard to bind all views, if the page renders ten views, the composer will get executed ten times. However, the approach looks good but it triggers queries multiple times.
How to overcome this issue?
Here I share chunks of code for better understanding.
This is a Service provider where bind the composer method. here use wild card * to bind variables in all views.
This is the method that is used to fetch data. when we @include any blade in the page at that time It triggers this method and it runs all queries under this method. we need to overcome this issue.
Here for reduce, this issue config can help us. When Compose method calls the first time set config so it will available every time.
And on every call need to check the config available or not based on these call queries. For that above code improvise as below.