Working With View Composers in Sage 10

Each Composer receives the $data variable, which is a keyed array. That Composer then adds keys and values to that array, and returns it. Each row in the array is then passed to the view, where each row is available as a variable with the name if that row’s key. Any views @included in that view will get the same data, which means their associated Composers will also get that data.

Let’s say I have a header.blade.php that looks like this:

// partials/header.blade.php
<header>
  {{ $title }}
  @include('partials.intro')
</header>

And its Composer has this:

// Composers/Partials/Header.php
public function with($data)
{
  return ['title' => 'Hello'];
}

So when the header is rendered, the $title variable will contain Hello.

The Composer for intro.blade.php could look like this:

// Composers/Partials/Intro.php
public function with($data)
{
  return ['intro' => $data['title'] . ' There'];
}

When the view intro.blade.php is rendered in header.blade.php, it will have access to a variable called $intro that contains Hello There. This is because when intro.blade.php is called in the context of header.blade.php, it has access to the same data that was passed to header.blade.php, which means its Composer also has access to that data, which is why we can concatenate that data in the Composer.

3 Likes