0

I have a site that has multiple instances (companies).

Each company can add their own inventory and unit number must be unique within instance (company). But I want to allow same unit number per company. Therefore, unit+ instance_id needs to be unique. Is there a way to implement this check in Request rules?

The following rule checks if unit already exists in the inventory. I need to add check for inventory.id AND inventory_instance_id

public function rules() {
    return [
        'unit' => 'unique:inventory|required|max:45',
        'comments' => 'sometimes|max:255'
    ];
}

public function messages() {
    return [
        'unit.unique' => 'Unit number already exists!',
        'unit.required' => 'Enter Unit Number!',
        'max' => ':attribute - Should not be longer than 255 symbols!'
    ];
}

2 Answers 2

2

The unique validation allows for many parameters. The syntax is roughly unique:table,column,except,idColumn,whereN,valueN.

The first parameter is the table, second is the field to be unique, third is an id to ignore, fourth is id column for the third parameter, and then the fourth and fifth (and six/seventh, etc...) allow you to specify additional where clauses for your unique validation. This is what you're looking for.

You can use the fourth and fifth parameters to specify that your unit must be unique within your specified instance id. Assuming your instance id is stored in inventory.instance_id and you have the value for that field in a variable called $instanceId, your rule would look something like:

public function rules() {
    $instanceId = 1;
    return [
        'unit' => 'unique:inventory,unit,NULL,id,instance_id,'.$instanceId.'|required|max:45',
        'comments' => 'sometimes|max:255'
    ];
}

As you may have guessed, one of your issues now is that your rule is dynamically generated. You will need to figure out a way to update your rule with the instance id you're checking for.

Sign up to request clarification or add additional context in comments.

Comments

0

Check this package: https://github.com/felixkiss/uniquewith-validator

I think it solves your problem.

1 Comment

wondering if there is a 'workaround' without additional packages

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.