A
A
Alexander Pankov2020-10-30 17:54:10
Laravel
Alexander Pankov, 2020-10-30 17:54:10

How to use one FormRequest to create and edit?

Hello, please tell me how to use one FormRequest to create and edit.
i want to create and update employee(employee) using one rules array
i have such rule in my EmployeeFormRequest

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


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

it works on update because $this->employee already exists via injection.
but the same rule does not work when creating, since we have an empty $employee in the controller until save is done.

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

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

then the creation of the record starts working, but the change does not, which is logical. (because I'm updating, let's say, not the name of an existing record, but another field, I submit the form, it validates the name, finds it and does not allow updating)

It is possible to somehow use one FormRequest for everything (create + update), but keep the uniqueness rule when creating and do not include it when updating if the field that is boring to me has not changed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pLavrenov, 2020-10-30
@pLavrenov

'name' => [
    "required",
    Rule::unique('employees')->ignore($name, 'name')
],

Can it be like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question