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

postitief's avatar

User javascript variable inside php blade

Hello,

I want to use a javascript variable inside php in a blade template. Probably explained a little bit wrong, so here is my code:

// Some HTML
<script>
    var javascriptNumber = $('#id').val();
    $("#response").html("{{ trans('messages.themessage', ['number' => javascriptNumber]) }}")
</script>

So, how to put javascriptNumber in the trans array.

0 likes
6 replies
bestmomo's avatar

Your Javascript variable is on client side, you cant use it in Blade.

RobinMalfait's avatar

You can't do that, php is executed before the page loads, your javascript when the page is done loading.

You should do a request to your server with the number and read the response.

in your route/controller you can then get the number and return the appropriate data.

davorminchorov's avatar

or you can put these values into a HTML data attribute (data-something="value") and just pick them up from the JS side.

sid405's avatar

@postitief Sometimes, in the view that is needs to implement this functionality i create a particular section

@section('footer_scripts')

<script>
    var javascriptNumber = $('#id').val();
    $("#response").html("{{ trans('messages.themessage', ['number' => javascriptNumber]) }}")
</script>
@stop

And then on the master layout, under the scripts i yield it.

@yield('footer_scripts')

This allows me to inject data from my views and have it render altogether with the javascript after the page has loaded. This will work in your case.

Just pay attention, as you're using jQuery, to place the yielded section under the jQuery import. You're good to go.

1 like

Please or to participate in this conversation.