Laravel 自定義表單驗證-自定義驗證規則

CrazyZard發表於2019-10-18

現在客戶表有2個手機欄位(phone,server_phone),不管插入還是編輯都需要對2個手機號進行驗證判重規則。但是如果用Laravel自己的unique規則的話,無法使用orWhere 方法。

Unique規則
select count ( * ) as aggregate from client where phone = '15706844651' and id <> '111111' and reserve_phone = '15706844651'

不符合在自己業務邏輯

建立自己的驗證規則檔案

<?php
namespace App\Validators;
use App\Models\Client\Client;
/**
 * Class PhoneValidator.
 */
class UniquePhoneValidator
{
    public function validate($attribute, $value, $parameters, $validator)
    {
        if($parameters){
            return Client::where(function ($query) use ($value){
                $query->where('phone',$value)->orWhere('server_phone',$value);
            })->whereNotIn('id',$parameters)->withTrashed() ? false : true;
        }
        return Client::where(function ($query) use ($value){
            $query->where('phone',$value)->orWhere('server_phone',$value);
        })->withTrashed() ? false : true;
    }
}

AppServiceProvider 中引入驗證

    protected $validators = [
        'unique_phone' => UniquePhoneValidator::class,
    ];

    public function boot()
    {
        $this->registerValidators();
    }

    protected function registerValidators()
    {
        foreach ($this->validators as $rule => $validator) {
            Validator::extend($rule, "{$validator}@validate");
        }
    }

在FormRquest 裡面中使用該規則

class MyClientRequest extends FormRequest
{
public function rules()
    {
        if($this->method() == 'POST'){
            return [
                'phone' => 'filled|int|unique_phone',
                'reserve_phone' => 'filled|int|unique_phone',
            ];
        } elseif ($this->method() == 'PUT'){
            return [
                'phone' => 'filled|int|unique_phone:'.$this->route('client'),
                'reserve_phone' => 'filled|int|unique_phone,'.$this->route('client'),
            ];
        }
    }
}

相關文章