I have the contracts table with (id, name, company) And my rules:
public function rules()
{
return [
'name' => 'required',
'company' => 'required'
];
}
When I create
Contract one with id = 1, name = A, company = C
Contract two with id = 2, name = A, company = C. It's wrong.
Because I want a company cannot have the same contract name.
If contract two with id = 2, name = B, company = C. It's Okay.
So I want know how custom name and company fields to those two columns bind each other
You can use custom rule closure for this.
public function rules()
{
return [
'name' => [
'required',
function($attribute, $value, $fail) use($this){
$exists = \DB::('contracts')->where('company', $this->company)->where('name', $this->name)->exists();
if(!exists){
$fail($attribute.'already added for this company.');
}
}
],
'company' => 'required'
];
}
I hope you understand.
You can see documentation here: https://laravel.com/docs/5.8/validation#custom-validation-rules
The following will work on the create
'name' => 'required|unique:contracts,name,'.$this->id.',NULL,id,company,'.$request->input('company')
The (undocumented) format for the unique rule is:
table[,column[,ignore value[,ignore column[,where column,where value]...]]]
Multiple "where" conditions can be specified, but only equality can be checked. A closure (as in the accepted answer) is needed for any other comparisons.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.