Laravel中通過ValidatesRequests這個trait來驗證requests非常的方便,并且在BaseController類中它被自動的引入了肝匆。
exitsts()和unique()這兩個規(guī)則非常的強大和便利。它們在使用的過程中需要對數(shù)據(jù)庫中已有的數(shù)據(jù)進行驗證,通常它們會像下面這樣來寫:
// exists example
'email' => 'exists:staff,account_id,1'
// unique example
'email' => 'unique:users,email_address,$user->id,id,account_id,1'
上面這種寫法的語法很難記捷雕,我們幾乎每次使用時叁鉴,都不得不去查詢一下文檔。但是從 Laravel 的5.3.18版本開始這兩個驗證規(guī)則都可以通過一個新的Rule類來簡化江醇。
我們現(xiàn)在可以使用下面這樣的熟悉的鏈式語法來達到相同的效果:
'email' => [
'required',
Rule::exists('staff')->where(function ($query) {
$query->where('account_id', 1);
}),
],
'email' => [
'required',
Rule::unique('users')->ignore($user->id)->where(function ($query) {
$query->where('account_id', 1);
})
],
這兩個驗證規(guī)則還都支持下面的鏈式方法:
- where
- whereNot
- whereNull
- whereNotNull
unique驗證規(guī)則除此之外還支持ignore方法濒憋,這樣在驗證的時候可以忽略特定的數(shù)據(jù)。
好消息是現(xiàn)在仍然完全支持舊的寫法陶夜,并且新的寫法實際上就是通過formatWheres方法在底層將它轉(zhuǎn)換成了舊的寫法:
protected function formatWheres()
{
return collect($this->wheres)->map(function ($where) {
return $where['column'].','.$where['value'];
})->implode(',');
}