Laravel's URL::to() vs URL::asset()

Short answer: No, not really.

You want to have the following code:

<script src="js/bootstrap.js"></script>

Now you can achieve this using blade syntax:

// using URL::to()
<script src="{{ URL::to('js/bootstrap.js') }}"></script>

// using URL::asset()
<script src="{{ URL::asset('js/bootstrap.js') }}"></script>

URL::to()

The method is implemented like this:

Laravel URL::to()

URL::asset()

The method is implemented like this:

Laravel URL::asset()

Difference

Both methods get the job done.

  • URL::to() additionally encodes the segments of the passed url with rawurlencode
  • URL::asset() removes index.php from the path (which shouldn’t be in first place)

So you get more utility by using URL::to(), but also takes longer to execute (approx. 25% more than URL::asset()). But it’s strongly neglectible, since calling 100 times URL::to() takes 0.003523 ms.

Alternatives

If you’re using blade, you can use the following to easily output style and script tags.

{{ HTML::script('js/bootstrap.js') }}
{{ HTML::style('css/bootstrap.min.css') }}

Or using any of Asset Management packages like orchestra/asset.

Simon Wicki

Simon Wicki is a Freelance Developer in Berlin. Worked on Web and Mobile apps at JustWatch. Fluent in Vue, Angular, React and Ionic. Passionate about Frontend, tech, web perf & non-fiction books.

Twitter Follow @zwacky