laravel 5嵌套路由问题

时间:2015-08-04 04:05:38

标签: php laravel laravel-5

Laravel 5的新手,并构建一个小的Rest测试应用程序。所以我想为一个控制器设想两个不同的端点。

/myApp/public/index.php/states/{state}/cities  //returns cities in a state

/myApp/public/index.php/states/{state}/cities/{city}  //will do somethin else

我有点不清楚如何为此设置路线。我想我可以让这些端点使用相同的控制器方法,但似乎更好的架构只是将每个端点路由到它自己的方法。

到目前为止,我有两件事情各自独立工作,但不能一起工作:

在routes.php中

//route to the first endpoint
Route::resource('states.cities', 'StatesController');
//routes to the second endpoint if first is uncommented,otherwise blank page with no errors in log
Route::resource('states.cities', 'StatesController@cities');

我的控制器代码的相关部分:

class StatesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request, $state)
    {
        //works
        $cities = States::where('state', '=', $state)->lists('name');
        echo json_encode($cities);
    }


    public function cities(Request $request, $state, $city)
    {
        echo "second request";
        echo $state;
        echo $city;
    }
    ......

任何人对正确处理此问题的方法有什么想法?干杯!

1 个答案:

答案 0 :(得分:3)

试试这个。

Route::get('states/{state}/cities', [
    'as' => 'state.cities',
    'uses' => 'StatesController@index'
]);

第二。

Route::get('states/cities/{state}/{city}', [
    'as' => 'city.of.state',
    'uses' => 'StatesController@cities'
]);

注意:在这种情况下,无需使用resource路由。 resource路线创建了您真正不需要的各种路线。 Resource controllers