簡體   English   中英

我如何在Laravel控制器中使用“ where”

[英]How can I use “where” in a Laravel controller

如果我有下一條路線:

Route::get('/user/{id}', function($id) {
    return View::make(users.profile, array('id' => $id));
})->where(array('id' => '[0-9]+'));`

我如何在Restful控制器中做同樣的事情?

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

我的UserController:

class UserController extends BaseController {

    public function getProfile($id) {
        return View::make('users.profile', array('id' => $id));
    }
}

感謝您的關注。

為了確保有關methodsURL的信息,請從您的終端運行php artisan routes ,以便獲得您可以使用其URL訪問的所有路由的列表。 在這種情況下,對於以下routecontroller您可能會找到一個類似於user/profile/10URL

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

// Controller
class UserController extends BaseController {

    public function getProfile($id) {

        return View::make('users.profile', array('id' => $id));
    }

}

因此,使用http://domain.com/user/profile/10 ,這里10將被傳遞到您的profile方法中的$id變量。 還要記住,在RESTfull控制器中,每個方法都應以它們響應的HTTP動詞作為前綴,因此在這種情況下,此方法將響應GET請求。

當鏈接到Route::controller調用時, where似乎不起作用,但是您可以使用Route::pattern聲明實現相同的功能。 因此,例如,Route :: controller的以下代碼(稱為“隱式路由”)將起作用,將id限制為數字:

Route::pattern('id', '\d+');
Route::controller('/user/{id}', 'UserController');

然后,在UserController中,將從GET請求中調用getIndex方法:

class UserController extends BaseController {
    public function getIndex($id) {
        return View::make('users.profile', array('id' => $id));
    }
}

但是請注意,這僅適用於index方法,即,對http:://example.com/user/99調用。 如果要使用其他通過“隱式路由”使用的控制器方法,例如http:://example.com/user/profile/99和控制器方法getProfile($id) ,則需要聲明您的路由而不使用{id}參數,如下所示:

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

...在這種情況下,您將無法使用->whereRoute::pattern來約束{id} ,因為沒有{id}參數可以約束。

最后,最好還是像在回答開始時那樣使用“顯式路由”,或者使用RESTful資源控制器( 請參閱docs )並將路由指定為:

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

如果您訂閱Laracasts,傑弗里路大約有一些“隱性路由”的危險的一個偉大的,明確的教程在這里

為了做到這一點,您想將Route::controller語句包裝在一個組中並為該組應用where模式,因為全局設置它對於其他路由可能不准確:

Route::group('where' => ['id' => '\d+'], function () {

   Route::controller('users', 'UsersController');
   // other restful controller definitions with this pattern go here

}

暫無
暫無

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

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