Laravel的unique和exists驗證規則的優化

本文是Laravel實戰:任務管理系統(一)的擴展閱讀php

原文連接; 歡迎做客咱們的php&Laravel學習羣:109256050laravel

Laravel中經過ValidatesRequests這個trait來驗證requests很是的方便,而且在BaseController類中它被自動的引入了。 exitsts()和unique()這兩個規則很是的強大和便利。它們在使用的過程當中須要對數據庫中已有的數據進行驗證,一般它們會像下面這樣來寫:數據庫

// 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版本開始這兩個驗證規則均可以經過一個新的Rule類來簡化。bash

咱們如今能夠使用下面這樣的熟悉的鏈式語法來達到相同的效果:post

'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);
    })
],
複製代碼

這兩個驗證規則還都支持下面的鏈式方法:學習

  • where
  • whereNot
  • whereNull
  • whereNotNull

unique驗證規則除此以外還支持ignore方法,這樣在驗證的時候能夠忽略特定的數據。ui

好消息是如今仍然徹底支持舊的寫法,而且新的寫法實際上就是經過formatWheres方法在底層將它轉換成了舊的寫法:this

protected function formatWheres()
{
    return collect($this->wheres)->map(function ($where) {
        return $where['column'].','.$where['value'];
    })->implode(',');
}
複製代碼

原文地址連接spa

相關文章
相關標籤/搜索