【问题标题】:Laravel routes for RESTful controllersRESTful 控制器的 Laravel 路由
【发布时间】:2012-12-24 11:11:16
【问题描述】:

具有以下控制器:

class Admin_Images_Controller extends Admin_Controller
{
    public $restful = true;

    public function __construct()
    {
        parent::__construct();
    }

    public function get_index($id)
    {
        echo $id;
    }

我不明白为什么当我在没有 ID 参数的情况下访问它时它会起作用,因为我收到一个错误说 missing parameter for ... 但是当我实际上尝试在 http://site/admin/images/12 传递参数时我收到 404 错误.我错过了什么?

我尝试在我的路线中设置以下内容,也没有成功:

Route::any('admin/images', array(
    'as' => 'admin_images',
    'uses' => 'admin.images@index',
));
    //or 
Route::any('admin/images/(:any)', array(
    'as' => 'admin_images',
    'uses' => 'admin.images@index',
));

我的通配符问题似乎有 90% 发生在我的测试 linux 环境 (ubuntu) 中。这是我目前正在使用的 routes.php http://pastebin.com/f86A3Usx

【问题讨论】:

    标签: php debugging http-status-code-404 laravel


    【解决方案1】:

    可能是您使用了相同的别名 (admin_images),而且,请检查您的订单 - 先放更具体的,然后越通用,如下所示:

    Route::any('admin/images/(:any?)', array('uses' => 'admin.images@index'));
    

    已删除别名,只是为了便于阅读。

    【讨论】:

    • 有路线,没有路线,按顺序路线......它不会去......任何其他方法(post_index,post_myass,put_fireonwate,get_image,get_alife)它都会去,但不是索引: |
    • 我忘记问号了。检查我的更新并尝试。这应该可行 - 如果不可行,就会出现其他问题。
    【解决方案2】:
    Route::get('admin/images/(:any)', 'admin.images@index');
    

    【讨论】:

    • 没有效果,而且我似乎在我的测试 Linux 环境(Ubuntu)上只有通配符有问题......并且在我的电脑上工作正常。这是我的完整路线。php pastebin.com/f86A3Usx
    【解决方案3】:

    您应该通过传递默认值(如 null/false/1)使 $id 参数成为可选参数

    public function get_index($id = null)
    {
        if($id){ 
            echo $id;
        }else{
            echo "No ID given!";
        }   
    }
    

    并在您的路线中使用 (:any?)。

    【讨论】:

      【解决方案4】:

      更新路线:

      Route::any('admin/images/(:any?)', array(
          'as' => 'admin_images',
          'uses' => 'admin.images@index',
      ));
      

      您可以通过组合每个端点的路由来简化路由。通过添加“?”进入你的第一个参数,这意味着任何东西都可以存在,但不是必须的。所以 /admin/images/admin/images/1234 都被覆盖了。

      更新的控制器:

      class Admin_Images_Controller extends Admin_Controller
      {
          public $restful = true;
      
          public function __construct()
          {
              parent::__construct();
          }
      
          public function get_index($id=null)
          {
              echo $id;
          }
      
          // ...
      }
      

      通过在您的方法参数中添加“= null”,您现在可以将两个路由都处理到此函数中。在您的方法中简单地检查“等于 null”应该会让您顺利覆盖每个场景。

      【讨论】:

        猜你喜欢
        • 2014-01-24
        • 2013-06-09
        • 2013-06-04
        • 2012-11-05
        • 1970-01-01
        • 2013-03-24
        • 1970-01-01
        • 2014-07-20
        • 1970-01-01
        相关资源
        最近更新 更多