【问题标题】:why Route::currentRouteName() not working in laravel 5 inside a controller method为什么 Route::currentRouteName() 在控制器方法中的 laravel 5 中不起作用
【发布时间】:2016-06-16 08:44:02
【问题描述】:

为什么 Route::currentRouteName() 在 laravel 5 中的控制器方法中不起作用,但是当我在类名起作用之前提供 '\' 时。我需要知道在这种情况下上课前添加反斜杠的原因。可能是一些糟糕的场景,我不知道。请指导

$name = \Route::currentRouteName();

【问题讨论】:

  • 你应该阅读命名空间。

标签: regex laravel routes


【解决方案1】:

您需要了解 PHP 命名空间的工作原理。

Route 不在控制器命名空间内,因此您需要为 Route 类提供完整的命名空间才能加载它。 Route 在根命名空间中,因此您可以使用 \Route 引用它,就像在目录结构中一样。

假设您的控制器如下所示:

<?php namespace App\Http\Controller
class HomeController extends Controller{

   public function index(){
      //Doing this will throw a Not Found exception because route is 
      //not inside `App\Http\Controller` namespace
      $name = Route::currentRouteName(); 

      //However if you specify the correct namespace it works like so:
      $name = \Route::currentRouteName(); 
   }

}

您可以在此处阅读有关命名空间的更多信息:

http://php.net/manual/en/language.namespaces.php

【讨论】:

  • 好的,感谢您的建议 @Digitlimit ,但在此语法中 \Route::currentRouteName();如果 \ 自从它在根 namspace 中被使用,但是为什么他们在他们的文档中给出了省略斜杠。并且 Route 在根命名空间中,那么我们不需要使用“use”关键字来包含它的命名空间。你能解释一下吗。我是新手,所以我需要一些指导
  • 如果您在 routes.php 中使用 Route,则不需要 \
【解决方案2】:

你可以使用

\Request::route()->getName()

\Route::getCurrentRoute()->getPath();

【讨论】:

  • 这并没有回答为什么需要 \ 的问题,他们已经意识到它似乎只有在使用它时才有效。
猜你喜欢
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
相关资源
最近更新 更多