用于REST的Laravel 4路由参数

时间:2013-10-09 13:22:26

标签: php rest laravel laravel-4 laravel-routing

这可能是一个简单的问题,但我正在使用Laravel进行测试。我相应地设置了这样的路线:

// Users Route
Route::get('users',array('as'=> 'users', 'uses'=> 'UsersController@index'));
Route::get('users/{id}', array('as' => 'user', 'uses' => 'UsersController@show') );
Route::get('users/{id}/edit', array('as' => 'edit_user', 'uses' => 'UsersController@edit') );
Route::get('users/new', array('as' => 'new_user', 'uses' => 'UsersController@create'));
Route::post('users',  'UsersController@create');
Route::delete('users', 'UsersController@destroy');

现在,在我的浏览器中,如果我访问localhost/users/new,它将调用名为“user”的路由而不是“new_user”。我的意思是,它将加载编辑路径而不是创建用户。

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:3)

如果您使用RESTful API,最好使用资源路由。

路线,

Route::resource('users', 'UsersController');

和控制器,

<?php


class UsersController extends BaseController {

    /**
     * Display all users.
     *
     * @return Response
     * GET http://localhost/laravel/users
     */

    public function index() {

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */

    public function create() {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     * POST http://localhost/laravel/users
     */

    public function store() {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     * GET http://localhost/laravel/users/1
     */

    public function show($id) {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */

    public function edit($id) {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     * PUT http://localhost/laravel/users/1
     */

    public function update($id) {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     * DELETE http://localhost/laravel/users/1
     */

    public function destroy($id) {


    }

}

答案 1 :(得分:2)

优先权很重要,只需改为:

Route::get('users',array('as'=> 'users', 'uses'=> 'UsersController@index'));
Route::get('users/new', array('as' => 'new_user', 'uses' => 'UsersController@create'));
Route::get('users/{id}', array('as' => 'user', 'uses' => 'UsersController@show') );
Route::get('users/{id}/edit', array('as' => 'edit_user', 'uses' => 'UsersController@edit') );
Route::post('users',  'UsersController@create');
Route::delete('users', 'UsersController@destroy');

Laravel认为'new'是你的{id}参数。