2017-03-24 1 views
1

트리거 될 때 DB 레코드를 가져 오기 다음 unique 검사가 해고L5.3 - 검사기 - '독특한'SI 내가 입력의 유효성을 검사 <code>Validator</code>을 사용하고

$validator = Validator::make($request->all(), [ 
    'short'   => 'required', 
    'name'   => 'required|unique:type_event,name' 
]); 

if ($validator->fails()) { 
    // fails validation 
} 

을의 id을받을 수있는 방법이 또는 DB에 이미 존재하는 레코드? 또는 예를 들어 모델을 다음과 같이 호출해야합니다.

$data = TypeEventModel::where('name', '=', $request->input('name'))->firstOrFail(); 

감사합니다.

+0

당신이'$ validator-를 인쇄 할 수 있습니다 사용할 수 있습니다 resources/lang/en/validation.php

'unique_with_id'=>'Same :entity exists with ID :id', 

에 다음과 같은 확인 메시지를 추가 > errors()'출력하여 여기에 붙여 넣으시겠습니까? –

+2

고유 한 유효성 검사기는 제공된 특성을 사용하여 카운트 쿼리를 수행하기 때문에 추가 쿼리를 직접 수행해야합니다. –

답변

0

먼저 사용자 지정 유효성 검사 규칙이 필요합니다. boot() 방법 app/Providers/AppServiceProvider.php에 다음 코드를 추가합니다 :

Validator::extend('unique_with_id', function ($attribute, $value, $parameters, $validator) { 
    // First we query for an entity in given table, where given field equals the request value 
    $found = DB::table($parameters[0]) 
     ->where($parameters[1], $value) 
     ->first(); 

    // then we add custom replacer so that it gives the user a verbose error 

    $validator->addReplacer('unique_with_id', function ($message, $attribute, $rule, $parameters) use ($found) { 
     // replace :entity placeholder with singularized table name and :id with duplicate entity's id 
     return str_replace([':entity', ':id'], [str_singular($parameters[0]), $found->id], $message); 
    }); 

    // finally return wether the entity was not found (the value IS unique) 
    return !$found; 
}); 

그런 다음 마지막으로 당신이

$validator = Validator::make($request->all(), [ 
    'short'   => 'required', 
    'name'   => 'required|unique_with_id:type_event,name' 
]); 
관련 문제