问题很简单,但答案似乎很难得到。在Codeigniter中,我可以加载URL助手,然后简单地执行
echo base_url();
获取我网站的URL。在Laravel中也有类似的情况吗?
问题很简单,但答案似乎很难得到。在Codeigniter中,我可以加载URL助手,然后简单地执行
echo base_url();
获取我网站的URL。在Laravel中也有类似的情况吗?
当前回答
2018年Laravel发行版(5.7)文档的更新,增加了更多url()函数及其用法。
问:在Laravel中获取该网站的URL ? 这是一个普遍的问题,所以我们可以把它分开。
1. 访问Base URL
// Get the base URL.
echo url('');
// Get the app URL from configuration which we set in .env file.
echo config('app.url');
2. 访问当前URL
// Get the current URL without the query string.
echo url()->current();
// Get the current URL including the query string.
echo url()->full();
// Get the full URL for the previous request.
echo url()->previous();
3.命名路由的url
// http://example.com/home
echo route('home');
4. 资产的url(公共)
// Get the URL to the assets, mostly the base url itself.
echo asset('');
5. 文件的url
use Illuminate\Support\Facades\Storage;
$url = Storage::url('file.jpg'); // stored in /storage/app/public
echo url($url);
这些方法也可以通过URL facade访问:
use Illuminate\Support\Facades\URL;
echo URL::to(''); // Base URL
echo URL::current(); // Current URL
如何使用刀片模板(视图)调用这些Helper函数。
// http://example.com/login
{{ url('/login') }}
// http://example.com/css/app.css
{{ asset('css/app.css') }}
// http://example.com/login
{{ route('login') }}
// usage
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- Login link -->
<a class="nav-link" href="{{ route('login') }}">Login</a>
<!-- Login Post URL -->
<form method="POST" action="{{ url('/login') }}">
其他回答
这样的:
echo url('/');
这:
echo asset('/');
在我的情况下,两者都显示了主页url:)
Laravel提供了很多帮助函数,根据你的需求,你可以简单地
使用Laravel Helpers的url()函数
但在Laravel 5.2中,你必须使用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;
}
Laravel < 5.2
echo url();
Laravel >= 5.2
echo url('/');
我用了这个,它在Laravel 5.3.18中为我工作:
<?php echo URL::to('resources/assets/css/yourcssfile.css') ?>
重要提示:这只会在你已经从你的URL中删除“公共”时起作用。要做到这一点,您可以查看这个有用的教程。