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


要获取当前 URL,您可以使用下面示例中说明的方法 -

示例 1

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Http\Response; class UserController extends Controller { public function index(Request $request) { return view('test'); } }

test.blade.php 文件如下 -

<!DOCTYPE html> <html> <head> <style> body { font-family: 'Nunito', sans-serif; } </style> </head> <body class="antialiased"> <div> @if (Request::path() == 'users') <h1>The path is users</h1> @endif </div> </body> </html>

test.blade.php 中,Request::path() 用于检查它是否指向用户,然后仅显示 h1 标签。Request::path() 返回正在使用的当前URL

示例 2

在本例中,让我们使用url()->current() 方法,如下例所示。url()->current() 提供当前 URL 的完整路径。

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index(Request $request) { return view('test'); } }

Test.blade.php

<!DOCTYPE html> <html> <head> <style> body { font-family: 'Nunito', sans-serif; } </style> </head> <body class="antialiased"> <div> @if (url()->current() == 'https://:8000/users') <h1>The path is users</h1> @endif </div> </body> </html>

执行上述示例后,它会在浏览器上打印以下内容 -

The path is users

示例 3

在本例中,我们将使用Request::url()。它的输出与url()->current() 相同,它返回完整的 URL,如下例所示 -

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index(Request $request) { return view('test'); } }

Test.blade.php

<!DOCTYPE html> <html> <head> <style> body { font-family: 'Nunito', sans-serif; } </style> </head> <body class="antialiased"> <div> @if (Request::url() == 'https://:8000/users') <h1>The path is users</h1> @endif </div> </body> </html>

执行上述示例后,它会在浏览器上打印以下内容 -

The path is users

示例 4

使用Request::is()

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index(Request $request) { return view('test'); } }

Test.blade.php

<!DOCTYPE html> <html> <head> <style> body { font-family: 'Nunito', sans-serif; } </style> </head> <body class="antialiased"> <div> @if (Request::is('users')) <h1>The path is users</h1> @endif </div> </body> </html>

在上面的示例中使用了Request::is()。如果给定的字符串存在于 URL 中,则返回 true/false。

执行上述示例后,它会在浏览器上打印以下内容 -

The path is users

更新于: 2022-08-30

1K+ 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.