I had a Employee form
for its validation while update I have created a validation request as EmployeeEdit
and while updating employee form content in controller I am passing this validation request to validate data.
but the employee form has various fields, which I have to check for uniqueness with different tables. for example, employee form has a emp_id field which i have to check for uniqueness in users table, mobile number to check-in employees table.
How to check uniqueness except for current id.
my rules in EmployeeEdit Request
return [
'emp_id' => 'nullable|max:255|unique:users,'.$this->get('emp_id'),
'code' => 'nullable|unique:employees|max:255'.$this->get('code'),
'mobile_number' => 'required|unique:employees|max:255,'.$this->get('mobile_number'),
];
My Controller:
public function doEdit(EmployeeEdit $request, $id)
{
echo "Validation passed";
exit;
}
Problem: I don't know how to pass these fields like emp_id, mobile_number from the request so that they are ignored for the current request and should be checked for other data for uniqueness.
use Illuminate\Validation\Rule;
return [
'emp_id' => [
'nullable',
'max:255',
Rule::unique('users', 'emp_id')->ignore(\Auth::user()->id),
],
];
Got the solution from @serhii comment
Now in EmployeeEdit Request
, i have added (on top)
use Illuminate\Validation\Rule;
public function rules()
{
return [
'emp_id' => ['nullable','max:255', Rule::unique('users', 'emp_id')->ignore($this->id)],
'code' => ['nullable','max:255', Rule::unique('employees', 'code')->ignore($this->id,'user_id')],
'mobile_number' => ['nullable','max:255', Rule::unique('employees', 'mobile_number')->ignore($this->id,'user_id')],
NOTE: Since the $this->id
is id from the users
table, in order to use it in employees table (which have user_id
as a foreign key) I have to explicitly define a column in employees
table rule.
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.