Home > Software design >  unique form validation based on two fields
unique form validation based on two fields

Time:09-27

I am creating a new record for a table named services including some fields (name, department_id, description) in database. I need unique combination of pair two fields together (name and department_id). How can I validate it for creating and updating functions?

In ServiceRequest:

return [
          'params.name' => 'required|unique:services,name and depatment_id',
       ];

In Service Model:

public function department()
{
    return $this->belongsTo(Department::class);
}

In DepartmentModel:

public function services()
{
    return $this->hasMany(Service::class);
}

In Route:

Route::apiResource('/services', ServiceController::class)->names([
    'store' => 'services_store',
    'update' => 'services_update',
]);

Forexample:

when there is a service in a specific department, it gives error! if there is a record of name = service1 and department_id = 1, user cannot create same record combination of name and department_id again! user allow to create service with (name = service1 and department_id = another_number) or (department_id = 1 and name = another_name) but creating a new record with (name = service1 and department_id = 1) is not allowed

CodePudding user response:

You can use the unique rule this way:

return [
    'params.name' => [
        'required', 
        Rule::unique('services', 'name')
            ->ignore($this->service)
            ->where('department_id', $this->input('params.department_id'))
     ],
];

Here you are telling Laravel to check if there is no existing record in the services table that have $this->input('params.name') as name and $this->input('params.department_id') as department_id.

The ->ignore($this->service) is here to make sure we ignore the current service (if we are updating), so it doesn't "find itself" during the validation.

$this->service will be the current instance you are updating (if you setup the routes and controllers correctly, which is another topic).

  • Related