<?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('/');
}
}
1
Laravel <5.2
echo url();
Laravel> = 5.2
echo url('/');
希望这对你有所帮助
2
对于Laravel 5,我通常使用:
<a href="{{ url('/path/uri') }}">Link Text</a>
我的理解是使用 url() 函数调用 Facade 作为 URL::to()
1
要使它与非漂亮的URL一起使用,我必须这样做:
asset('/');
1
另一种可能性: {{ URL::route('index') }}
1
更新了2018年Laravel版本(5.7)文档以及更多url()函数及其用法 .
问题:要在Laravel中获取网站的URL?这是一个普遍的问题,所以我们可以分开它 .
1. Accessing The 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. Accessing The Current 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. URLs For Named Routes
// http://example.com/home
echo route('home');
4. URLs To Assets(Public)
// Get the URL to the assets, mostly the base url itself.
echo asset('');
5. File URLs
use Illuminate\Support\Facades\Storage;
$url = Storage::url('file.jpg'); // stored in /storage/app/public
echo url($url);
Each of these methods may also be accessed via the URL facade:
use Illuminate\Support\Facades\URL;
echo URL::to(''); // Base URL
echo URL::current(); // Current URL
How to call these Helper functions from blade Template(Views) with usage.
14 回答
Laravel提供了大量的帮助功能,您可以简单地满足您的要求
使用Laravel Helpers的 url() 功能
但是在 Laravel 5.2 的情况下你将不得不使用 url('/')
here是Laravel的所有其他帮助程序函数的列表
这个:
还有这个:
在我的情况下都显示了主页:)
您可以使用URL facade来调用URL generator
所以你可以这样做:
您还可以使用应用程序容器:
或者注入UrlGenerator:
Laravel <5.2
Laravel> = 5.2
希望这对你有所帮助
对于Laravel 5,我通常使用:
我的理解是使用
url()
函数调用Facade
作为URL::to()
要使它与非漂亮的URL一起使用,我必须这样做:
另一种可能性:
{{ URL::route('index') }}
更新了2018年Laravel版本(5.7)文档以及更多url()函数及其用法 .
1. Accessing The Base URL
2. Accessing The Current URL
3. URLs For Named Routes
4. URLs To Assets(Public)
5. File URLs
Each of these methods may also be accessed via the URL facade:
How to call these Helper functions from blade Template(Views) with usage.
要获取您配置的应用程序网址,您可以使用Config :: get('app.url')
我用过这个,它在Laravel 5.3.18中为我工作:
重要说明:仅当您已从网址中删除"public"时,此功能才有效 . 为此,您可以查看this helpful tutorial .
您还可以使用URL :: to('/')在Laravel中显示图像 . 请看下面:
假设您的图像存储在“公共/图像”下 .
顺便说一下,如果您的路线有如下名称:
您可以像这样使用
route()
函数:其他有用的功能:
https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php
您可以按照以下方式使用外墙或辅助功能 .
我找到了另一种方法来获取基本URL以显示环境变量APP_URL的值
这将显示基本网址,如http://domains_your//yours_website . 请注意,它假定您已在.env文件中设置环境变量(存在于根文件夹中) .