Laravel 4.默认控制器路由不接受参数

时间:2013-12-23 06:50:56

标签: php laravel-4

我有一个RESTful控制器供我的用户处理用户个人资料的查看。

问题在于:

我希望网址看起来像www.example.com/user/1

这将向用户显示id为1.问题是当我在UserController中定义getIndex方法时,它不会接受id作为参数。

这是我的routes.php部分:

Route::controller('user', 'UserController');

现在,我的理解是,如果url中没有提供其他内容,则getIndex是一种默认路由,所以这个:

public function getIndex() {

}
UserController中的

将接受路由,

"www.example.com/user/index" 

"www.example.com/user"

它确实!

但是,如果我在网址中包含一个应该从网址中获取的参数,它就不再起作用了:

public function getIndex($id) {
    //retrieve user info for user with $id
}

这只会响应

"www.example.com/user/index/1" 

而不是

"www.example.com/user/1"

我怎样才能让后者奏效?如果没有必要的话,我真的不想用“索引”这个词弄乱网址。

2 个答案:

答案 0 :(得分:0)

如果您打算这样做,最好的方法是使用RESTful控制器。

将路线改为此路线

Route::resource('user', 'UserController');

然后使用php artisan命令

生成控制器
php artisan controller:make UserController

这将生成具有所有RESTful功能的控制器

<?php

class UserController extends \BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index() // url - GET /user (see all users)
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create() 
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store() // url - POST /user (save new user)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id) // url - GET /user/1 (edit the specific user)
    {
        //
    }

    /**
     * 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
     */
    public function update($id) // url - PUT /user/1 (update specific user)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id) // url - DELETE /user/1 (delete specific user)
    {
        //
    }

}

有关详细信息,请参阅此Laravel RESTful controller parameters

答案 1 :(得分:0)

要在地址栏上显示www.example.com/user/1,您应该使用show方法。在Laravel中,restful controller默认创建7条路由。 Show就是其中之一。

控制器中的

会创建如下方法:

public function show($id) 
{
    // do something with id

    $user = User::find($id);
    dd($user);
}

现在,浏览http://example.com/user/1