Laravel & Alpine.js | DOM elements for writing Alpine.js code based on PHP conditions
P粉763748806
P粉763748806 2023-08-06 11:54:24
0
1
499

<p>This updateSoftwareRequest returns this data on error: </p> <pre class="brush:php;toolbar:false;"> public function after(): array { return [ function (Validator $validator) { If ($ validator-& gt; failed ()) {                            $validator->errors()->add('model', $this->route('software')); session(['showUpdateSoftwareModal', true]);             }                                    ]; } </pre> <p>I want this span to get an x-init based on the session value. I'm trying to do it like this: </p> <pre class="brush:html;toolbar:false;"> <span x-data="{}" x-on:click="$dispatch('open-modal', 'edit-software-modal ')" data-type="edit" {{ session('showUpdateSoftwareModal') === true ? 'x-init="console.log('HI')"' : '' }}>Edit</span> ; </pre> <p>But when the value is true, x-init will not trigger the write. Can anyone help? <br /><br />Edit: Just found this in the documentation: <br /><br />You can add x-init inside or outside the x-data HTML block in any element. For example:<br /><br />Does anyone know of other solutions? I'm trying to retrigger an edit modal where the fields within the modal are taken from data properties on the parent td of the button on click. The error trigger is coming from a form request and I'm trying to trigger a button for a specific row. </p>

P粉763748806
P粉763748806

reply all(1)
P粉350036783

There seems to be a problem with the quotes because they are escaped by blade's {{ }}, so they should be changed to:

{{ session('showUpdateSoftwareModal') === true ? 'x-init="console.log(\'HI\')"' : '' }}

Can use:

{!! session('showUpdateSoftwareModal') === true ? 'x-init="console.log(\'HI\')"' : '' !!}

But I suggest you take a different approach:

<span x-data="{myFlag: {{ (int)session('showUpdateSoftwareModal', false) }} }"
      @click="$dispatch('open-modal', 'edit-software-modal')"
      data-type="edit"
      x-init="if (myFlag) {console.log('HI')}"
>
  Edit
</span>

This way you can use myFlag anywhere in the Alpine object.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template