[英]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));
}
}
感谢您的关注。
为了确保有关methods
和URL
的信息,请从您的终端运行php artisan routes
,以便获得您可以使用其URL
访问的所有路由的列表。 在这种情况下,对于以下route
和controller
您可能会找到一个类似于user/profile/10
的URL
// 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');
...在这种情况下,您将无法使用->where
或Route::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.