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

PHPz
发布: 2023-08-23 14:14:02
转载
964 人浏览过

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

要获取当前URL,您可以使用下面示例中解释的方法−

示例1

<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsUser; use IlluminateHttpResponse; 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 AppHttpControllers; use IlluminateHttpRequest; use AppModelsUser; 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() == 'http://localhost:8000/users') <h1>The path is users</h1> @endif </div> </body> </html> 
登录后复制

在执行上面的示例时,它会在浏览器上打印以下内容−

The path is users
登录后复制
登录后复制
登录后复制

示例3

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

<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsUser; 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() == 'http://localhost:8000/users') <h1>The path is users</h1> @endif </div> </body> </html> 
登录后复制

在执行上面的示例时,它会在浏览器上打印以下内容−

The path is users
登录后复制
登录后复制
登录后复制

示例4

使用 Request::is()

<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsUser; 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() 被使用。它会返回 true/false,表示给定的字符串是否存在于 URL 中。

在执行上面的示例时,它会在浏览器上打印以下内容−

The path is users
登录后复制
登录后复制
登录后复制


以上是在Laravel的@if语句中如何获取当前URL?的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!