Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jasonlbeggs/1341e7367c0dc69ac64ef2140d0f0591 to your computer and use it in GitHub Desktop.
Save jasonlbeggs/1341e7367c0dc69ac64ef2140d0f0591 to your computer and use it in GitHub Desktop.

Pass Alpine.js Bound Attributes To Blade Component

If you need to pass a bound Alpine.js attribute to a Laravel Blade component, you can prefix the attribute name with two colons instead of a single colon to tell Blade to not evaluate the attribute as a PHP expression.

<div x-data="{ isActive: true }">
    <x-some-blade-component ::is-active="isActive" />
</div>
@sentiasa
Copy link

TLDR;

<div x-data="{ isActive: true }">
    <x-some-blade-component is-active="isActive" />
</div>
<button :disabled="{{ $attributes->get('is-active') }}">

</button>

As the blade gets compiled before the javascript is activated, you get your html ready. At this point, your components are expanded within the html. Only after that the Alpine gets run. That means as long as you have the binding on your component, it will work.

So to summarise, your compiled blade gets turned into this:

<div x-data="{ isActive: true }">
    <button is-active="isActive"></button>
</div>

at this moment, alpine doesn't know if it's component or not anyways, so just having the attribute will make it accessible by the Alpine.

@elias-g-m
Copy link

elias-g-m commented Nov 22, 2023

In case you are wondering, the solution is right from the laravel docs here
Escaping Attribute Rendering

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment