问题很简单,但答案似乎很难得到。在Codeigniter中,我可以加载URL助手,然后简单地执行
echo base_url();
获取我网站的URL。在Laravel中也有类似的情况吗?
问题很简单,但答案似乎很难得到。在Codeigniter中,我可以加载URL助手,然后简单地执行
echo base_url();
获取我网站的URL。在Laravel中也有类似的情况吗?
当前回答
您也可以使用URL::to('/')在Laravel中显示图像。请参阅以下内容:
<img src="{{URL::to('/')}}/images/{{ $post->image }}" height="100" weight="100">
假设,您的图像存储在“public/images”下。
其他回答
这样的:
echo url('/');
这:
echo asset('/');
在我的情况下,两者都显示了主页url:)
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') }}">
您可以使用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
Laravel < 5.2
echo url();
Laravel >= 5.2
echo url('/');