Mai Rich
Mai Rich

Reputation: 81

How to use Laravel URL::to in Javascript?

I'm trying to access this laravel URL inside Javascript:

var id = 2;
var href = '{{ URL::to('/bus/'+ id +'') }}';

I tried to escape the single quote and \ before it, like this:

var id = 2;
var href = '{{ URL::to(\'/bus/'+ id +'') }}';

It's giving me this error:

Parse error: syntax error, unexpected ''/bus/'' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING)

Upvotes: 1

Views: 115

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Aside from the mis-matched quotes, id is a client-side JS variable which is not available in your Laravel logic which runs on the server. To fix this get the URL to /bus on the server, then append the id to it on the client. Something like this:

var id = 2;
var href = '{{ URL::to('/bus/') }}' + id;

Note that you may need to append a / between the Laravel output and the id value, it just depends on how the routes are generated.

Upvotes: 3

Related Questions