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>
@titosen
Copy link

titosen commented Aug 18, 2021

I've been looking for this the whole day.

Thank you very much.

@rickdubiel
Copy link

What a life saver!!!! Can't find this solution anywhere at all!! Just stumbled upon this after LOTS and LOTS of looking. Thank you so much for posting this!

@cftiangco
Copy link

Hi how do you read is-active variable data inside component?

@onemoreahmad
Copy link

onemoreahmad commented Mar 25, 2023

Hmm this doesn't seem to work. The some-blade-component component won't receive the actual value coming from Alpinejs.

Please replay if it did work for you.

** If the reason is just to let Laravel component to ignore the attribute for the sake of Alpinejs, then you always could use the full bind attribute provided by Alpine, x-bind:is-active="..".

@gavinhewitt
Copy link

Hmm this doesn't seem to work. The some-blade-component component won't receive the actual value coming from Alpinejs.

Please replay if it did work for you.

** If the reason is just to let Laravel component to ignore the attribute for the sake of Alpinejs, then you always could use the full bind attribute provided by Alpine, x-bind:is-active="..".

Doesn't seem to work for me either :-(

@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