我有一个URL: http://localhost:8888/projects/oop/2
我想访问第一个段落 --> projects
我已经尝试过
<?php echo $segment1 = Request::segment(1); ?>
当我刷新页面时,我的视图中没有打印任何内容。
非常感谢您的任何帮助/建议
我有一个URL: http://localhost:8888/projects/oop/2
我想访问第一个段落 --> projects
我已经尝试过
<?php echo $segment1 = Request::segment(1); ?>
当我刷新页面时,我的视图中没有打印任何内容。
非常感谢您的任何帮助/建议
试试这个
{{ Request::segment(1) }}
基于LARAVEL 5.7及以上版本
获取当前URL的所有部分:
$current_uri = request()->segments();
从http://example.com/users/posts/latest/中获取段posts
注意: 段是以索引0开始的数组,数组的第一个元素从网址的顶级域名(TLD)后开始。因此,在上面的网址中,segment(0)将是users
,segment(1)将是posts
。
//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'
你可能已经注意到,segment()
方法只能在当前 URL (url()->current()
) 上起作用。因此,我设计了一个方法,通过克隆 segment()
方法来与之前的 URL 一起使用:
public function index()
{
$prev_uri_segments = $this->prev_segments(url()->previous());
}
/**
* Get all of the segments for the previous uri.
*
* @return array
*/
public function prev_segments($uri)
{
$segments = explode('/', str_replace(''.url('').'', '', $uri));
return array_values(array_filter($segments, function ($value) {
return $value !== '';
}));
}
segments()
返回一个从0开始的数组,但如果你调用segment()
方法,索引是从1开始的,所以segment(1)
将是"users",segment(2)
将是"posts"。在典型的Laravel风格中,在文档中根本没有提到这一点,但segment()
方法的文档注释"从URI中获取一个段(基于1的索引)"确认了这一点。 - rob74双花括号通过 Blade 进行处理,而不是纯 PHP。这种语法基本上会输出计算出的值。
{{ Request::segment(1) }}
以下是如何通过全局的request
帮助函数完成此操作。
{{ request()->segment(1) }}
注意:request()
返回 Request
类的对象。
$segments = request()->segments();
$last = end($segments);
$first = reset($segments);
这里是代码,你可以获取 URL 段。
{{ Request::segment(1) }}
{!! Request::segment(1) !!}
use Request;
放在最上面吗? - code-8