Laravel 7 introduced Blade components using x- syntax. This is pretty cool feature and gives additional functionality comparing to what we know from Laravel 6. But let’s focus on passing content to components and see what is available.
Let’s assume we have component like this:
1 2 3 4 5 6 7 |
{{-- components/header.blade.php -- }} <h1 class="page-header my-4 text-gray-900"> <span> {{ $slot }} </span> </h1> |
In Laravel 6 we had to use it like this:
1 2 3 |
@component('header') New page header @endcomponent |
But in Laravel 7 we can use it like this:
1 2 3 |
<x-header> New page header </x-header> |
For me it looks much cleaner. But what if we could just inline text in attribute and use cleaner syntax?
Well, that’s possible, but we have to update our component code to rename $slot into any other name we want to use, for example:
1 2 3 4 5 6 7 |
{{-- components/header.blade.php -- }} <h1 class="page-header my-4 text-gray-900"> <span> {{ $text}} </span> </h1> |
Then we can pass content to component like this:
1 |
<x-header text="New page header" /> |
If we have text in variable then we should add colon before attribute name like so:
1 |
<x-header :text="$headerAssignedToVariable" /> |
This is pretty cool. We can use single line to pass some data into component. Much cleaner than it was in Laravel 6.
But what in case we would like to make our component more flexible? Let’s assume in some cases we just want to pass just text (and use attribute to to this) but in others we would like to pass custom HTML markup we want to put into component content.
We would like to use our component like this:
1 |
<x-header text="New page header" /> |
but also like this:
1 2 3 |
<x-header> <svg>...</svg> <strong>New</strong> page header </x-header> |
depending on our needs.
Well, it’s not available out of the box, but it’s pretty easy to achieve. If we rewrite our component like so:
1 2 3 4 5 6 7 |
{{-- components/header.blade.php -- }} <h1 class="page-header my-4 text-gray-900"> <span> {{ $text ?? $slot }} </span> </h1> |
it will be now possible to use both ways of passing data depending on our needs. We can use just single line to pass content as attribute but when we need to pass more complex content, we can use slot functionality.