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

pimous's avatar

How to use the function url() in a js file

Hello, I would like to use the function url() in a javascript file, because I don't want to write in hard the URL.

I tried something like that but it doesn't work :

url = <?php url('file/file2') ?>

Somebody has a solution ?

0 likes
9 replies
sharrpenized's avatar

Also, you might need quotes around it if its JS:

var url = "<?php echo url('file/file2'); ?>";
sitesense's avatar

:D

// note the quotes
url = '<?php echo url('file/file2') ?>'

// or maybe even
url = '{!! url('file/file2') !!}'
pimous's avatar

All the solutions doesn't work :(

//Doesn't work, if I do an alert, I have nothing
url = '<?php echo url('file/file2') ?>';
url = '{!! url('file/file2') !!}';

//Doesn't work, if I do an alert, write this : .../public/<?php echo url('file/file2'); ?>
var url = "<?php echo url('file/file2'); ?>";
sitesense's avatar

You need to do this within <script> tags in your layout view. Are you trying to load this through an external js file?

<script>
    var url = "<?php echo url('file/file2'); ?>";
</script>
pmall's avatar
pmall
Best Answer
Level 56

@pimous

All the solutions doesn't work :(

It doesnt work in a js file as they are not parsed.

You have to put this in a blade template between script tags. Because the blade template is parsed so php is interpreted.

The strategy is to declare all your variables in the blade file then pass them to a js function defined in your js file.

yan_ever's avatar

it is a subject that dates a long time ago but I still come with my element of response in your view blade header you can do it

<divtype="hidden" id="path" value="url('/')">

and in all your js or jquery file , you make

var path = $("#path").val();

and when you want to put url , just do

example : href="'+path+'/nameofroute"

Please or to participate in this conversation.