In Laravel 5, What's the difference between {{url}} and {{asset}}?

我与影子孤独终老i 提交于 2019-11-30 08:35:45

Deciding which URL helper to use

Consider the type of URL that is needed / how the URL is being used. One of the advantages of having separate helper methods for each type of URL is they can have different handling logic. For example, assets (e.g. CSS, images, etc.) could involve a check that the file exists in the file system but do not require the type of analysis that a route would because the route may have parameters.

url() Generates an absolute URL to the given path (code)

  • Use for static URLs (which should be rare).
  • Accepts array of parameters that are encoded and added to the end of the domain.
  • Preserves any URL query string.

    {{ url('search') }}
    // http://www.example.com/search
    
    {{ url('search', ['qevo', 'laravel']) }}
    // http://www.example.com/search/qevo/laravel
    

asset() Generates a URL to an application asset (code)

  • Use for files that are directly served such as CSS, images, javascript.
  • Only accepts a direct path.

    {{ asset('css/app.css') }}
    // http://www.example.com/css/app.css
    

route() Gets the URL to a named route (code)

  • Use for every route (every route should be named to help future-proof path changes).
  • Requires named routes.
  • Accepts associative array for route parameters.
  • Allows override for relative route vs. absolute route (default).

    {{ route('user.profile', ['name'=>'qevo']) }}
    // http://www.example.com/user/qevo/profile
    
    {{ route('user.profile', ['name'=>'qevo'], false) }}
    // /user/qevo/profile
    

{{url}} allows you to create a link to a URL on your site -- another benefit is the fact that you can set the second parameter to an array with query string parameters within.

{{asset} simply allows you to link to an asset within your public directory -- for example css/main.css.

Fefar Ravi

asset() method is used to include CSS/JavaScript/images files.

url() method used to generate an URL to a link.

Example asset:

this would be

<script src="{{ asset('js/jquery.min.js') }}"></script>

Example url:

this would be

{{ url('image/welcome.png') }}
tisuchi

URL::route gets the URL to a named route. So in your case if you name your route like this:

Route::get('/account/register', [
    'name' => 'register', 
    'uses' => 'RegisterController@create'
]);

then you will be able to use

<a href="{{ URL::route('register') }}" >Register 1</a> in Blade templates.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!