【问题标题】:How to access URL segment(s) in blade in Laravel 5?如何在 Laravel 5 中访问刀片中的 URL 段?
【发布时间】:2015-10-28 05:56:25
【问题描述】:

我有一个网址:http://localhost:8888/projects/oop/2

我要访问第一段 --> projects

我试过了

<?php echo $segment1 = Request::segment(1); ?>

当我刷新页面时,我的视图中没有打印任何内容。


任何帮助/建议将不胜感激

【问题讨论】:

  • 你使用过Request namaspace吗?
  • 是的。我应该在某处声明吗?我该怎么做?
  • @ImtiazPabel :我应该把它放在顶部吗use Request;

标签: php laravel laravel-5 blade


【解决方案1】:

试试这个

{{ Request::segment(1) }}

【讨论】:

  • 它和我的有什么不同?只是出于好奇。
  • @ihue 不是。 Blade 将在内部将 "{{" 转换为 ""。因此,它与您正在做的事情完全相同,并且会以同样的方式工作。
【解决方案2】:

双花括号是通过 Blade 处理的——不仅仅是普通的 PHP。这种语法基本上与计算值相呼应。

{{ Request::segment(1) }} 

【讨论】:

    【解决方案3】:

    基于 LARAVEL 5.7 及以上版本

    获取当前 URL 的所有片段:

    $current_uri = request()->segments();

    从http://example.com/users/posts/latest/获取段posts

    注意: 段是从索引 0 开始的数组。数组的第一个元素在 url 的 TLD 部分之后开始。所以在上面的 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'
    

    您可能已经注意到,segment 方法仅适用于当前 URL (url()->current())。所以我通过克隆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 !== '';
        }));
    }
    

    【讨论】:

      【解决方案4】:

      这里是如何通过全局 request 辅助函数来实现的。

      {{ request()->segment(1) }}

      注意:request()返回Request类的对象。

      【讨论】:

        【解决方案5】:

        一种获取第一个或最后一个段的简单方法,以防您不确定路径长度。

        $segments = request()->segments();
        $last  = end($segments);
        $first = reset($segments);
        

        【讨论】:

          【解决方案6】:

          这是您可以获取 url 段的代码。

          {{ Request::segment(1) }}
          

          如果您不想转义数据,请使用 {!! !!} 否则使用 {{ }}。

          {!! Request::segment(1) !!}
          

          https://laravel.com/docs/4.2/requests

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-12-18
            • 2015-04-16
            • 2017-08-19
            • 2021-07-06
            • 2015-07-06
            • 2017-08-19
            • 1970-01-01
            • 2023-02-26
            相关资源
            最近更新 更多