+1 vote
by
Hello, could you please tell me how to use one FormRequest to create and edit.
I want to create and update an employee using one array of rules
I have this rule in my EmployeeFormRequest

'name' => "required|unique:employees,name,{$this->employee->id}"


the name is mandatory, unique within its own table by name, do not count the current employee.

it works when updating because $this->employee via injection already exists.
But this rule does not work when creating, because we have an empty $employee in the controller, until you make a save.

if you remove the rule "to exclude the current one", so

'name' => "required|unique:employees,name"

then creating a record starts working, but changing it does not, which is logical. (because I'm updating not the name of the existing record, but another field, I sub-mix the form, it validates the name, finds it and does not let me update it)

Is it possible to use one FormRequest for everything (create + update), but keep the uniqueness rule when creating and not include it when updating if the field I need has not changed?

1 Answer

0 votes
by
'name' => [
"required",
Rule::unique('employees')->ignore($name, 'name')
],
You can do this.
...