Laravel View Composer duplicating SQL queries for every view bind. How it runs once?

Why does this happen?

The 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.




Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Learn JDBC By Project — Part III

CS371p Spring 2021 Week 3

7 Best Redmine Hosting in 2020 comparison of top providers

Product Review — Notion

Mocking others can harm you

Getting started with Kotlin on Android

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dipesh Sukhia

Dipesh Sukhia

Software Engineer

More from Medium

Using Fetch/Post with React and Laravel API

The Typed Data API, by example

GitHub - mglaman/drupal-typed-data-by-example: Drupal's Typed Data API by example

How to create CRUD operation with CodeIgniter 4 and React JS

Stores with Dependency Injection in Vue 2 with Inversify