Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

itsAsyc's avatar

Using php inside a javascript function that is being executed in a blade component event

Hello,

I know the title might sound confusing, but I hope I manage to explain myself properly.

I currently have a blade view with different components. In one of these I want to perform a fetch() when a value has been picked from a dropdown.

@component('company::components.form.select', [
    'name' => 'warehouse_id',
    'required' => true,
    'label' => trans('Almacen'),
    'icon' => 'warehouse',
    'options' => $warehouses,
    'event' => '@form-select-warehouseid-changed.window="getDeletionData"'
])@endcomponent

And getDeletionData is being declared at the end of the blade file, in a script tag, such as:

function getDeletionData($event) {
    const warehouseId = $event.detail.value;
    const url = new URL('{{ route('company.api.stocks.clear.countdeletions') }}');
    url.searchParams.append('warehouse_id', warehouseId);
    fetch(url)
        .then(response => response.json())
        .then(data => {
            // Handle the response data here
            const movementsInputField = document.querySelector('input[name=\'movements\']');
            const stocksInputField = document.querySelector('input[name=\'stocks\']');
            movementsInputField.value = data.movements_count;
            stocksInputField.value = data.stocks_count;
        });
}

My line manager has told me not to follow this approach because all the components in the rest of the projects have the js code directly written down where my current getDeletionData would be.

Due to single quotes, double quotes, trying to get a php variable (route(...)) is just a huge mess, and no matter how hard I try, I just cannot put this code in the component

@component('company::components.form.select', [
    'name' => 'warehouse_id',
    'required' => true,
    'label' => trans('Almacen'),
    'icon' => 'warehouse',
    'options' => $warehouses,
    'event' => '@form-select-warehouseid-changed.window="
		const warehouseId = $event.detail.value;
		//...
"'
])@endcomponent

A hand is greatly appreciated, as I am quite frustrated for both not being able to follow a much more clear and easier to maintain code style, and also not being able to put the code there directly, no matter how many quotes i escape, etc, I just can't.

Thank you

0 likes
12 replies
Snapey's avatar

Sorry I dont understand how the two blocks of code are related or what php code you need

you have {{ route('company.api.stocks.clear.countdeletions') }} passed as a simple string (with no quotes) passed to the html but you want to change this or do it differently somehow?

itsAsyc's avatar

@Snapey Hello, thanks for answering.

A screenshot might be better to understand my problem, but I can't post links as it is my first day after signing up.

I will split the URL so that you can recompose it (if it is against the rules, I will edit this, sorry, I'm frustrated). http s://i.im gur.c om/eCQS0Ef.png

There are so many quotes that I am not able to make this work.

kokoshneta's avatar
Level 27

I don’t think there’s a pretty way to do this, but if they’re really insisting that the entire JavaScript function must be inlined into the @component directive, I think explicit string concatenation is your only viable option. Ugly as all hell, but…

This should work, in theory:

@component('company::components.form.select', [
    'name' => 'warehouse_id',
    'required' => true,
    'label' => trans('Almacen'),
    'icon' => 'warehouse',
    'options' => $warehouses,
    'event' => '@form-select-warehouseid-changed.window="
		function($event) {
			const warehouseId = $event.detail.value;
			const url = new URL(\'' . route('company.api.stocks.clear.countdeletions') . '\');
			…
		}
	"
'
])@endcomponent

Remember that everything inside the brackets in the @component() directive is plain PHP, not Blade, so you can’t use {{ }} to echo out things – you just use the call to route() directly, making sure to first end the string and then restart it again afterwards.

Snapey's avatar

you could try concatenation?

@component('company::components.form.select', [
   'name' => 'warehouse_id',
   'required' => true,
   'label' => trans('Almacen'),
   'icon' => 'warehouse',
   'options' => $warehouses,
   'event' => "@form-select-warehouseid-changed.window=\"
		const warehouseId = $event.detail.value;
       const url = new URL('" . route('company.api.stocks.clear.countdeletions') . ");
       url.searchParams.append('warehouse_id', warehouseId);
       fetch(url)
         .then(response => response.json())
         .then(data => {
           // Handle the response data here
           const movementsInputField = document.querySelector('input[name=\'movements\']');
           const stocksInputField = document.querySelector('input[name=\'stocks\']');
           movementsInputField.value = data.movements_count;
           stocksInputField.value = data.stocks_count;
       });"
])
@endcomponent


kokoshneta's avatar

@Snapey Jinx! (You have a missing single quote after the second concat marker, though, to close the string parameter to URL(). And if you’re going to switch the single and double quotes, you need to escape the dollar signs in the JavaScript variable names, \$event – otherwise it’ll be interpreted as PHP and you’ll probably get a missing variable exception.)

itsAsyc's avatar

@Snapey Doing this throws an error, as php is trying to use the a variable called $event Undefined variable: event.

Snapey's avatar

@kokoshneta not surprising. I'm typing with one finger on an ipad.

I tried to switch it because of all the single quotes in the string already. My preferred approach would actually be sprintf.

My initial confusion was because of @component which i have not seen since laravel 5.5

itsAsyc's avatar

@kokoshneta Im currently fighting with it, yours seems to be working better, I'm just having another issue now.

I had to add a () => { ... code ... } on top of the js snippet and now im fighting with the quotes on the query selector

() => {
    const warehouseId = $event.detail.value;
    const url = new URL(\'' . route('company.api.stocks.clear.countdeletions') . '\');
    url.searchParams.append(\'warehouse_id\', warehouseId);
    fetch(url)
        .then(response => response.json())
        .then(data => {
            // Handle the response data here
            const movementsInputField = document.querySelector(\'input[name=\\"movements\\"]\');
            const stocksInputField = document.querySelector(\'input[name=\\"stocks\\"]\');
            movementsInputField.value = data.movements_count;
            stocksInputField.value = data.stocks_count;
        });
    }

Im getting this console error Uncaught SyntaxError: '' string literal contains an unescaped line break.

itsAsyc's avatar

Update, removing all those \" I was trying to add fixes everything ...

This is the final version ...

@component('company::components.form.select', [
    'name' => 'warehouse_id',
    'required' => true,
    'label' => trans('Almacen'),
    'icon' => 'warehouse',
    'options' => $warehouses,
    'event' => '@form-select-warehouseid-changed.window="() => {
    const warehouseId = $event.detail.value;
    const url = new URL(\'' . route('company.api.stocks.clear.countdeletions') . '\');
    url.searchParams.append(\'warehouse_id\', warehouseId);
    fetch(url)
        .then(response => response.json())
        .then(data => {
            // Handle the response data here
            const movementsInputField = document.querySelector(\'input[name=movements]\');
            const stocksInputField = document.querySelector(\'input[name=stocks]\');
            movementsInputField.value = data.movements_count;
            stocksInputField.value = data.stocks_count;
        });
    }
"'
])@endcomponent

Thank you guys!

kokoshneta's avatar

@itsAsyc See my updated answer. I meant to include that from the start, but forgot – when you define the whole thing inline, of course you need to tell the JavaScript engine that it’s an anonymous function, but as long as you make sure that your strings start and end in the right places, that shouldn’t be a problem.

1 like

Please or to participate in this conversation.