簡體   English   中英

Laravel 4.默認控制器路由不會接受參數

[英]Laravel 4. default controller route wont accept arguments

我有一個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"

確實如此!

但是,如果我包含一個應從url中獲取的參數,它將不再起作用:

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

這只會回應

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

並不是

"www.example.com/user/1"

我怎樣才能使后者工作? 我真的不想在不必要的情況下使用“索引”一詞來修飾網址。

如果您打算這樣做,最好的方法是使用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控制器參數

要在地址欄上顯示www.example.com/user/1 ,應使用show方法。 在Laravel中,靜態控制器默認創建7條路由。 表演是其中之一。

在您的控制器中創建如下方法:

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

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

現在,瀏覽http://example.com/user/1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM