Siddharth
Siddharth

Reputation: 1769

Multiple Duplicated Queries - Laravel

I'm first showing the code written in my controller:

public function __construct(Utility $utility)
{
 $league = $utility->checkDomainController();
 view()->share('league', $league);
 $this->league = $league;
}

public function getDashboard()
{
 return view('dashboard.dashboard', compact('activities'));
}

Now I want to share $league in all the views in the methods present there in the controller. ( $league consists of one query only ).

But now what problem I'm facing is, query gets duplicated with the number Included Views with the Main View. Here dashboard is the main view. So now if 7 views are included in Main View then query on $league gets executed 7 times. Below are the pictures:

Picture of views included in dashboard.blade.php Picture of views included in dashboard.blade.php

Picture of Queries getting duplicated Picture of Queries getting duplicated

Any solution to this? Any better way to handle this?

Upvotes: 0

Views: 2680

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

A few solutions open to you.

One solution would be to cache the query. Only efficient if your $league data does not frequently change.

$league = Cache::remember('users', $minutes, function () {
    return $utility->checkDomainController();
});

Another solution would be to use View Composer. It will be called only when that specific view is rendered. So if you include it once, it renders once.

View::composer('leagues', function ($view) {
    //
});

Read more about view composers here: https://laravel.com/docs/5.4/views#view-composers

Upvotes: 1

Related Questions