Blade components 101

I've been using Blade components since they were added back in Laravel 5.4. For those who don't know what a Blade component is, it's a directive to include views inspired by “components” in JavaScript frameworks like Vue.

A component's injected contents—placed in the “main slot”—are available through a $slot variable. Other data can be passed via an associative array similar to @include. What's nice about plain variables is that you can easily transform them or fall back to a default value, which is a bit more verbose using @section in layouts.

We can also share component “properties” via the @slot directive. This is useful if we need to pass a chunk of html or any other large string to the component.

This is pretty cool. We can now build apps by composing components, a more coherant model than traditional layouts & includes.

Introducing component aliases

I had one issue with Blade components—they can be annoyingly verbose at times.

Compare a Vue.js component with the previous alert example:

<alerttype="warning"title="Beware!">
Here be dragons!
</alert>

This is much leaner than @component('path.to.component', ...). A similar html-like syntax in Blade would be a bad idea, but that's okay. Blade's has a simple syntax: print things with curly brackets and do all the other things with directives. Let's keep it that way.

What if we could simplify the component syntax to a single directive? this is possible with the new Blade::component function.