Laravel: Get base url

后端 未结 17 1764
梦谈多话
梦谈多话 2020-12-07 10:09

Simple question, but the answer seems quite hard to come by. In Codeigniter, I could load the url helper and then simply do

echo base_url();
<
相关标签:
17条回答
  • 2020-12-07 10:24

    To just get the app url, that you configured you can use :

    Config::get('app.url')
    
    0 讨论(0)
  • 2020-12-07 10:24

    You can use facades or helper function as per following.

    echo URL::to('/');
    echo url();
    

    Laravel using Symfony Component for Request, Laravel internal logic as per following.

    namespace Symfony\Component\HttpFoundation;
    /**
    * {@inheritdoc}
    */
    protected function prepareBaseUrl()
    {
        $baseUrl = $this->server->get('SCRIPT_NAME');
    
        if (false === strpos($this->server->get('REQUEST_URI'), $baseUrl)) {
            // assume mod_rewrite
            return rtrim(dirname($baseUrl), '/\\');
        }
    
        return $baseUrl;
    }
    
    0 讨论(0)
  • 2020-12-07 10:27

    Laravel provides bunch of helper functions and for your requirement you can simply

    use url() function of Laravel Helpers

    but in case of Laravel 5.2 you will have to use url('/')

    here is the list of all other helper functions of Laravel

    0 讨论(0)
  • 2020-12-07 10:27

    I found an other way to just get the base url to to display the value of environment variable APP_URL

    env('APP_URL')
    

    which will display the base url like http://domains_your//yours_website. beware it assumes that you had set the environment variable in .env file (that is present in the root folder).

    0 讨论(0)
  • 2020-12-07 10:27

    you can get it from Request, at laravel 5

    request()->getSchemeAndHttpHost();
    
    0 讨论(0)
  • 2020-12-07 10:29

    This:

    echo url('/');
    

    And this:

    echo asset('/');
    

    both displayed the home url in my case :)

    0 讨论(0)
提交回复
热议问题