问题很简单,但答案似乎很难得到。在Codeigniter中,我可以加载URL助手,然后简单地执行

echo base_url();

获取我网站的URL。在Laravel中也有类似的情况吗?


当前回答

您也可以使用URL::to('/')在Laravel中显示图像。请参阅以下内容:

<img src="{{URL::to('/')}}/images/{{ $post->image }}" height="100" weight="100"> 

假设,您的图像存储在“public/images”下。

其他回答

您可以使用URL facade,它允许您调用URL生成器

所以你可以这样做:

URL::to('/');

你也可以使用应用程序容器:

$app->make('url')->to('/');
$app['url']->to('/');
App::make('url')->to('/');

或者注入UrlGenerator:

<?php
namespace Vendor\Your\Class\Namespace;

use Illuminate\Routing\UrlGenerator;

class Classname
{
    protected $url;

    public function __construct(UrlGenerator $url)
    {
        $this->url = $url;
    }

    public function methodName()
    {
        $this->url->to('/');
    }
}

另一种可能:{{URL::route('index')}}

你可以从laravel 5的请求处得到

request()->getSchemeAndHttpHost();

Laravel < 5.2

echo url();

Laravel >= 5.2

echo url('/');

您可以按照以下方法使用facade或helper函数。

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

Laravel使用Symfony组件进行请求,Laravel内部逻辑按 追随者。

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;
}