I am currently using a Laravel Provider
to pass data to a view each time it is called. The App.blade.php
includes the blade file if the user is authenticated.
My problem is that at the moment, no matter what view the user is on, it still calls the ViewServiceProvider.php
, which doesn't seem very efficient.
I have tried to use @if(view()->exists('home'))
, but that doesn't seem to have any effect what so ever, and thus, the queries are still called from the ViewServiceProvider.php
.
App.blade.php:
@if(!Auth::guest())
@if(view()->exists('home'))
@include('layouts.check')
@endif
@endif
ViewServiceProvider.php:
public function boot()
{
view()->composer('layouts.check', function ($view) {
$sites = Site::where('trust_id', Auth::id())->get();
$view->with(['sites' => $sites]);
});
}
Any help would be hugely appreciated.
The problem with you code is that it's check to see if the view exists. Chances are, the view "home" will always exist, so it will always include your view; "layouts.check".
Unless, of course, the view "home" is dynamic and is only there conditionally, which doesn't seem right. If you want the "layouts.check" view file to only load on certain pages, you might want to try "Request::is()".
@if(Request::is('home'))
@include('layouts.check')
@endif
The view composer is going to be called whenever your 'layouts.check' view is rendered.
Even though you've attempted to not have it rendered (by adding in your if statements), the view is still going to be rendered, and your view composer is still going to be called.
The template engine is going to parse your view in one pass. The engine doesn't care about any type of logic inside you're view, it's only job is to convert that logic into PHP code. So, even though you have the statement @if(!Auth::guest())
, the parser doesn't understand the actual logic, it just knows to convert that to <?php if (!Auth::guest()) { </php>
.
Basically, your @if
statements aren't preventing the engine from parsing your include file, it is the parsed PHP code that prevents the results of the include file from showing in your output. So, since your @include
file is parsed, the view composer is called.