asset() vs url()
What is the difference between the two and in which cases I should use one or another?
asset() - Generate a URL to an application asset.
url() - Generate a URL to an named route.
the asset() method is used to include CSS/JavaScript/images files, you can use it in this cases
<link href="{{ asset('css/min.css') }}" rel="stylesheet">
<script src="{{ asset('use.typekit.net/zjb5wvv.js') }}"></script>
<img alt="logo" src="{{ asset('images/logo.png') }}">
The files must located in the public folder.
the url() method used to generate an url to a link,
{{ url('users', ['page' => 22], $secure = null) }}
Both methods are helpers that point to Illuminate\Routing\UrlGenerator class' methods (asset and to), the big differences are:
asset($path, $secure = null)
-
asset doesn't accept extra query parameters
- in case of relative URL
asset checks for presence of index.php string and removes it because is not needed for assets
url/to($path, $extra = [], $secure = null)
-
to does accept extra parameters that are appended as path segments
-
to preservers query string
Try this in artisan tinker:
>>> url('relativeurl?existingparam=1',['newparam'=>2])
=> "http://phpdev/subdir/public/relativeurl/2?existingparam=1"
both
- accept absolute path starting with
\#, //, http, mailto, tel , for them it only checks for validity
Please or to participate in this conversation.