如何在Laravel 4中的@if语句中获取当前URL?

345
我正在使用Laravel 4。我想在使用Laravel的Blade模板引擎时,在视图中的@if语句内访问当前URL,但我不知道如何做。
我知道可以使用类似于<?php echo URL::current(); ?>的方法来实现,但在@if Blade语句内部不可能这样做。
有什么建议吗?

以下任何答案是否有助于解决您的问题? - N69S
30个回答

7
在 Blade 模板文件中
@if (Request::is('companies'))
   Companies name 
@endif

6

与其使用 URL::path() 来检查当前路径位置,您可能希望考虑使用 Route::currentRouteName()。这样,如果您更新了路径,您就不需要再浏览所有页面以更新路径名称。


5

1. 检查URL是否为X

简单来说,您需要检查URL是否与X完全相同,然后显示某些内容。在控制器中:

if (request()->is('companies')) {
  // show companies menu or something
}

在 Blade 文件中 - 几乎完全相同:
@if (request()->is('companies'))
  Companies menu
@endif

2. 检查URL是否包含X

一个稍微复杂的示例 - 方法Request::is()允许使用pattern参数,例如:

if (request()->is('companies/*')) {
  // will match URL /companies/999 or /companies/create
}

3. 按名称检查路由

正如您可能知道的那样,每个路由都可以分配一个名称,在routes/web.php文件中,它看起来像这样:

Route::get('/companies', function () {
  return view('companies');
})->name('comp');

那么如何检查当前路由是否为“comp”呢?相对容易:

if (\Route::current()->getName() == 'comp') {
  // We are on a correct route!
}

4. 通过路由名称进行检查

如果您正在使用路由名称,您可以检查请求是否匹配路由名称。

if (request()->routeIs('companies.*')) {
  // will match routes which name starts with companies.
}

或者

request()->route()->named('profile')

将匹配名为 "profile" 的路由。 因此,这是检查当前URL或路由的四种方式。

来源


问题涉及 Laravel 4,基于 Laravel 9 的教程。Request::is('companies') 是 Laravel 4 中的实现方式。 - Joundill

4

使用 Laravel 的 path 可以另一种方式来编写 if 和 else 语句。

 <p class="@if(Request::is('path/anotherPath/*')) className @else anotherClassName @endif" >
 </p>

希望能对您有所帮助。

2

试试这个:

@if(collect(explode('/',\Illuminate\Http\Request::capture()->url()))->last() === 'yourURL')
    <li class="pull-right"><a class="intermitente"><i class="glyphicon glyphicon-alert"></i></a></li>
@endif

感谢您提供这段代码片段,它可能会提供一些有限的、即时的帮助。通过展示为什么这是一个好的解决方案,一个适当的解释将极大地提高其长期价值,并使其对未来读者具有其他类似问题更有用。请[编辑]您的答案以添加一些解释,包括您所做出的假设。 - jhpratt

2

适用于 Laravel 5.5 +

<a class="{{ Request::segment(1) == 'activities'  ? 'is-active' : ''}}" href="#">
                              <span class="icon">
                                <i class="fas fa-list-ol"></i>
                              </span>
                            Activities
                        </a>

1

有许多方法可以实现,其中我经常使用的一种

 Request::url()

1

Try This:

<li class="{{ Request::is('Dashboard') ? 'active' : '' }}">
    <a href="{{ url('/Dashboard') }}">
 <i class="fa fa-dashboard"></i> <span>Dashboard</span>
    </a>
</li>


1
@if(request()->path()=='/path/another_path/*')
@endif

虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - rollstuhlfahrer

0
尝试这种方式:
<a href="{{ URL::to('/registration') }}">registration </a>

请在您的答案中添加一些解释 - Pankaj Makwana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接