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

echo base_url();

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


当前回答

您可以按照以下方法使用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;
}

其他回答

有多种方法:

请求()- > getSchemeAndHttpHost () url(“/”) 资产(“) 配置(“app.url”) $ _SERVER(“SERVER_NAME”)

要获得应用程序的url,你可以使用:

Config::get('app.url')

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

request()->getSchemeAndHttpHost();

您可以使用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('/');
    }
}

顺便说一下,如果你的路线有一个这样的名字:

Route::match(['get', 'post'], 'specialWay/edit', 'SpecialwayController@edit')->name('admin.spway.edit');

你可以像这样使用route()函数:

<form method="post" action="{{route('admin.spway.edit')}}" class="form form-horizontal" id="form-spway-edit">

其他有用功能:

$uri = $request->path();
$url = $request->url();
$url = $request->fullUrl();
asset()
app_path();
// ...

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php