folcotandiono's avatar

laravel url

i have many javascript variable, then i have laravel url wrote in javascript (var url = "{{URL::to('.../...')}}"), how to pass this javascript variable to this url, notice that {{ }} is php.

0 likes
4 replies
biishmar's avatar

@folcotandiono

In blade file open script tag and assign variable before ur external javascript..

Blade file

//at the end
<script>
    var url = {{ URL::to('.../...') }};
</script>
<script src="yourexternaljs"></script>
folcotandiono's avatar

@biishmar

var abcd = "1234";

var url = {{ URL::to('abcd') }};

i want the url become {{ URL::to('1234') }};

how to do that?

biishmar's avatar

@folcotandiono

when your script runs its not going to like

var url = {{ URL::to('abcd') }};

it changes to

var url = www.yoursite.com/abcd;

because those things already runs in server and changes to url, if u want to change now

str_replace('abcd', '1234', url );


Nash's avatar
Nash
Best Answer
Level 20

var abcd = "1234"; var url = {{ URL::to('abcd') }}; i want the url become {{ URL::to('1234') }}; how to do that?

You can't pass a JS variable to a PHP function like that. Just do the URL like this:

var url = "/1234"; // this will work just fine

Or if you want the absolute URL, you could do something like:

<script>
    // This can be used as your base url anywhere in your JS code
    window.base_url = "{{ URL::to('/') }}";
</script>

...

<script>
    // Elsewhere in your code...
    var abcd = "/1234";
    var url = window.base_url + abcd;
</script>

You could even make a JS function that uses the window.base_url (or some other) variable and acts like Blade's URL helper.

Please or to participate in this conversation.