如何动态获取当前URL的最后一部分,不包括斜杠/
标记?
例如:
在www.news.com/foo/bar
中获取bar
。
在www.news.com/foo/bar/fun
中获取fun
。
将该函数放置在何处或如何在当前视图中实现?
如何动态获取当前URL的最后一部分,不包括斜杠/
标记?
例如:
在www.news.com/foo/bar
中获取bar
。
在www.news.com/foo/bar/fun
中获取fun
。
将该函数放置在何处或如何在当前视图中实现?
request()->segment(count(request()->segments()))
last
。像这样:last(request()->segments())
。{{ collect(request()->segments())->last() }}
使用 basename()
与 Request::path()
一起使用。
basename(request()->path())
既然request()
是Laravel中的全局辅助函数,而basename()
是一个标准的PHP函数,并且也是全局可用的,因此您应该能够从代码的任何位置调用它。
路由对象是您想要的信息来源。有几种方法可以获取信息,其中大多数涉及将某些内容传递给您的视图。我强烈建议不要在Blade中完成工作,因为这就是控制器操作的用途。
向Blade传递值
最简单的方法是使路由的最后一部分成为参数,并将该值传递给视图。
// app/Http/routes.php
Route::get('/test/{uri_tail}', function ($uri_tail) {
return view('example')->with('uri_tail', $uri_tail);
});
// resources/views/example.blade.php
The last part of the route URI is <b>{{ $uri_tail }}</b>.
// app/Http/routes.php
Route::get('/test/uri-tail', function (Illuminate\Http\Request $request) {
$route = $request->route();
$uri_path = $route->getPath();
$uri_parts = explode('/', $uri_path);
$uri_tail = end($uri_parts);
return view('example2')->with('uri_tail', $uri_tail);
});
// resources/views/example2.blade.php
The last part of the route URI is <b>{{ $uri_tail }}</b>.
使用request helper在Blade中完成所有操作。
// app/Http/routes.php
Route::get('/test/uri-tail', function () {
return view('example3');
});
// resources/views/example3.blade.php
The last part of the route URI is <b>{{ array_slice(explode('/', request()->route()->getPath()), -1, 1) }}</b>.
尝试使用request()->segment($number)
,它应该会给你一个URL的片段。
在你的例子中,根据URL的分段数,可能应该是request()->segment(2)
或request()->segment(3)
。
您的控制器:
use Illuminate\Support\Facades\URL;
file.blade.php:
输出 basename(URL::current());
它对我很有用:
request()->path()
来自 www.test.site/news
获取 -> 新闻
我刚刚有同样的问题。与此同时,Laravel 8已经发布。我总结了我所知道的所有可能性。
您可以在Web路由中进行测试:
http(s)://127.0.0.1:8000/bar/foo || baz
http(s)://127.0.0.1:8000/bar/bar1/foo || baz
Route::get('/foo/{lastPart}', function(\Illuminate\Http\Request $request, $lastPart) {
dd(
[
'q' => request()->segment(count(request()->segments())),
'b' => collect(request()->segments())->last(),
'c' => basename(request()->path()),
'd' => substr( strrchr(request()->path(), '/'), 1),
'e' => $lastPart,
]
)->where('lastPart', 'foo,baz'); // the condition is only to limit
我更喜欢选择方案e)。
正如@Qevo在他的答案中已经写过的,你只需要将最后一部分作为请求的一部分。为了进一步缩小范围,你可以将WHERE条件放在路由上。
尝试使用:
{{ array_pop(explode('/',$_SERVER['REQUEST_URI'])) }}
它应该能够很好地工作。