View Composer data not available when assigned to layout
I was taking the advice of @Snapey and @Cronix to assign my View Composer to my master layout, instead of a wildcard, but it doesn't seem to be working.
ComposerServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* @return void
*/
public function boot()
{
View::composer(['layouts.app'], function ($view) {
$year = \App\Year::where('is_current', '1')->first();
$view->with('year', $year);
...
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
ErrorException (E_ERROR)
Undefined variable: year (View: /home/vagrant/code/resources/views/campcost.blade.php)
I can see from the debug bar that the ComposerServiceProvider database calls are not happening. Any ideas?
@extends('layouts.app')
@section('title')
Camp Cost Calculator
@endsection
@section('heading')
Use this tool to easily estimate the cost of your fees for {{ $year->year }}.
@endsection
...
Aha, that's it @tykus . Is there a way to pass it into the yielded views or do I need to change the @yield to @include directives and pass in the data manually?
A good idea @tykus but I still hit the same problem with child views either a) not having access due to scope or b) running the composer more than once, defeating the purpose of the optimization. I'm beginning to think composers were just not meant to house database calls.
I understand. Last shot... service injection will allow you to extract the computation of the $year to a class and @inject it in any view template that requires it. Not sure if your query is sufficiently complex to necessitate service injection, but you get the idea.