【问题标题】:laravel 4 cannot get into the specify controller methodlaravel 4 无法进入指定控制器方法
【发布时间】:2013-09-27 09:21:08
【问题描述】:
  1. 我的路线.php

    Route::get('course/{id}', 'CourseController@show');
    
    Route::get('course/{id}/{comment_type}', 'CourseController@show');
    
    Route::get('course/search/{key_word}', 'CourseController@search');
    
  2. 我的 CourseController.php 有这些方法

    public function show($id,$comment_type=1)
    {
      //do something
    }
    
    public function search($key_word)
    {
     //do something
    }
    
  3. 我想进入search 方法。但每次我调用

    course/search/{key_word} //search method in CourseCOntroller
    

    进入

    course/{id}/{comment_type} //show method in CourseCOntroller
    
  4. 我调试源代码。而且我发现UrlMatcher有一个matchCollection函数,我找到了原因,laravel生成了一个错误的Regular Expression 当我调用course/search/{key_word} 时,它会生成这样的正则表达式?

    #^/course/(?P<id>[^/]++)/(?P<comment_type>[^/]++)$#s
    
  5. 不知道这个正则表达式是怎么产生的。

  6. 我该如何解决这个问题,当我调用 course/search/{key_word} 时它会调用 search 方法。

【问题讨论】:

    标签: php regex laravel laravel-4


    【解决方案1】:

    改变你的路线顺序:

    <?php
    Route::get('course/search/{key_word}', 'CourseController@search');
    Route::get('course/{id}/{comment_type}', 'CourseController@show');
    Route::get('course/{id}', 'CourseController@show');
    

    因为 {id} 是通配符,它​​会选择每条路线。

    参见http://laravel.com/docs/routing#route-parameters -> '正则表达式路由约束' 或者路由模型绑定@http://laravel.com/docs/routing#route-model-binding

    【讨论】:

    • 嗯,是的。在自定义路由绑定上使用 ->where() 你可以随心所欲地扭曲它;)
    猜你喜欢
    • 2022-01-09
    • 2013-06-02
    • 2016-04-04
    • 2014-03-09
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多