[英]How to use regular expressions with resources in Laravel 4
如果我們使用Laravel 4創建簡單的路線,則可以使用where為每個參數設置正則表達式。 在URI中傳遞。 例如:
Route::get('users/{id}',function($id){
return $id;
})->where('id','\d+');
對於每個獲取請求,第二個參數。 必須是數字。 當我們創建資源時,問題就來了,如果我們使用->where()
則會引發有關該對象不是對象的錯誤。
我試圖將位置放置在一個組中,作為第三個參數的數組。 如何使用正則表達式的功能以及Laravel 4資源的功能?
他喬斯,
我一直在同一個問題發瘋,所以我做了一些研究。 我只能得出以下結論:您不需要此方法。 在每個控制器方法中,您可以在每個參數后指定默認值:
public function getPage(id = '0', name = 'John Doe'){
下一步,您可以使用正則表達式檢查,以及使用laravel驗證程序進行許多其他檢查,如下所示:
//put the passed arguments in an array
$data['id'] = $id;
$data['name'] = $name;
//set your validation rules
$rules = array(
"id" => "integer"
"name" => "alpha"
);
// makes a new validator instance with the data to be checked with the given
// rules
$validator = Validator::make($data, $rules);
// use the boolean method passes() to check if the data passes the validator
if($validator->passes()){
return "stuff";
}
// set a error response that shows the user what's going on or in case of
// debugging, a response that confirms your above averages awesomeness
return "failure the give a response Sire";
}
由於大多數驗證已經在laravel的選項列表中 ,因此您可能不需要正則表達式檢查。 但這是一個選項(正則表達式:模式)。
在控制器中不存在where()方法的背后,我的理論是該方法為您提供了在Route文件中進行驗證的機會。 由於您的控制器中已經具有這種可能性,因此就不需要它了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.