Have you tried to use caching? So the query will only be called once in a while
Executing a View Composer only once
I'm working on a project where we have View Composers attached to multiple views rendered on the same page. The composer and it's queries are executed multiple times. I want it to run only once to optimize performance.
I.e. the ContactPageComposer might look up the link and contents of the site's contact page and can be attached the top and bottom navigation views. However, the ContactPageComposer would be ran twice.
I've looked around and some say it can't be done and a Laravel 4 solution doesn't work with our L5 application.
I feel like there is a possibility to do this, but I haven't found it yet.
Eureka!
What I forgot about singletons is that while the same object is returned every time, the compose function is still called multiple times. With that in mind, I've found this solution:
In ComposerServiceProvider:
public function register()
{
$this->app->singleton(\App\Http\Composers\CountriesComposer::class);
}
And the composer class itself:
namespace App\Http\Composers;
use Illuminate\Contracts\View\View;
use App\Country;
class CountriesComposer
{
private $countries;
public function compose(View $view)
{
if (!$this->countries) {
$this->countries = Country->all();
}
return $view->with('countries', $this->countries);
}
}
Please or to participate in this conversation.