使用 Laravel 時,我們都會用到 `url()` 產生超連結 (hyper link),使用 `url()`所產生的 URL 會是完整的 URL,即包括有 Protocol、Domain、Port、Path 及 Query String 所有資料。 ### 完整的 URL 以下是一個完整的 URL ```text https://19site.com:80/posts?page=2 ``` - https - Protocol - 19site.com - Domain - :80 - Port number - /posts - Path - ?page=2 - Query String 使用 Laravel 的 `url('/posts')` 產生的 URL 會是以下的樣子。 ```php // laravel url() helper function echo url('/posts'); // https://19site.com/posts ``` ### 相對的 URL 如果我們要用 `url()` 來產生相對 (relative) 的 URL,最直接是不使用 `url()` 就可以解決了 ! 但如果我們硬是要使用 `url()` 的方式來產生 URL 的話,就需要自己再外建 helper function 了。 ```php /** * create relative url */ function relativeUrl($value='') { return str_replace(url(''), '', url($value)); } // use new helper function echo relativeUrl('/posts'); // /posts ```