mwal
mwal

Reputation: 3113

Does Laravel View::composer() risk calling same data twice?

If I have a view partial which always needs the same data (say to fill out some nav links) and I provide that data in a view composer, do I need to worry about cases where the main page also needs, and loads, this data? In other words, is it possible to end up duplicating a db query if you're not careful?

Upvotes: 0

Views: 345

Answers (2)

mwal
mwal

Reputation: 3113

Summary of how I understand this now:

If a partial needs data not used elsewhere in your view, you don't add the call for that to the controller, but to a composer registered on that partial. All this does for you is get the call out of your controller, to reduce the volume of code there: nothing more. (though if the partial is called by more than one view, it keeps your code DRY).

If a partial needs data which is also used on other parts of your page, you should think twice about adding a view composer, as it won't allow you to remove the call for that data, and will just mean you need a duplicate call as will need to pass the variable from your controller in any case (due to scope not being shared, as explained in my comment on the question above).

Upvotes: 0

short answer is yes, you might call for the same data twice.

try adding

DB::enableQueryLog();

before any database calls, and in the end, before the view is returned, do this:

var_dump(DB::getQueryLog());

Then you can see if you are calling the same data twice, in the query log.

Upvotes: 1

Related Questions