[英]How to access URL segment(s) in blade in Laravel 5?
I have a url : http://localhost:8888/projects/oop/2
我有一个网址:
http://localhost:8888/projects/oop/2
I want to access the first segment --> projects
我想访问第一段 -->
projects
I've tried我试过了
<?php echo $segment1 = Request::segment(1); ?>
I see nothing print out in my view when I refresh my page.刷新页面时,我在视图中看不到任何打印内容。
Any helps / suggestions will be much appreciated任何帮助/建议将不胜感激
尝试这个
{{ Request::segment(1) }}
The double curly brackets are processed via Blade -- not just plain PHP.双大括号是通过 Blade 处理的——不仅仅是普通的 PHP。 This syntax basically echos the calculated value.
此语法基本上与计算值相呼应。
{{ Request::segment(1) }}
BASED ON LARAVEL 5.7 & ABOVE基于 Laravel 5.7 及以上
To get all segments of current URL:获取当前 URL 的所有段:
$current_uri = request()->segments();
To get segment posts
from http://example.com/users/posts/latest/从http://example.com/users/posts/latest/获取分段
posts
NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url.注意:段是从索引 0 开始的数组。数组的第一个元素在 url 的 TLD 部分之后开始。 So in the above url, segment(0) will be
users
and segment(1) will be posts
.所以在上面的 url 中,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'
You may have noted that the segment method only works with the current URL ( url()->current()
).您可能已经注意到,segment 方法仅适用于当前 URL (
url()->current()
)。 So I designed a method to work with previous URL too by cloning the segment()
method:所以我设计了一种方法来通过克隆
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 !== '';
}));
}
Here is how one can do it via the global request
helper function.下面是如何通过全局
request
帮助函数来做到这一点。
{{ request()->segment(1) }}
Note: request()
returns the object of the Request
class.注意:
request()
返回的是Request
类的对象。
Here is code you can get url segment.这是您可以获得 url 段的代码。
{{ Request::segment(1) }}
If you don't want the data to be escaped then use {!!如果您不想转义数据,请使用 {!! !!} else use {{ }}.
!!} 否则使用 {{ }}。
{!! Request::segment(1) !!}
https://laravel.com/docs/4.2/requests https://laravel.com/docs/4.2/requests
An easy way to get the first or last segment, in case you are unsure of the path length.获取第一个或最后一个段的简单方法,以防您不确定路径长度。
$segments = request()->segments();
$last = end($segments);
$first = reset($segments);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.