Is it possible to pass the unique validation method extra where clauses with a variable?
Heres an example:
In my model I have my validation rules.
Defined my own class, so the existing rules declared in the class can stay.
protected $rules = array(
"id" => 'unique_custom:data_groups,id,id=GroupId'
);
Then added a magic method for Laravel:
public function getGroupIdAttribute() {
return $this->id;
}
In the service provider boot method:
\Illuminate\Support\Facades\Validator::extend('unique_custom', '\Module\UniqueDataValidator@validate');
Then added the class to src folder for package:
'The :attribute field must be unique',
);
/**
* Validate the uniqueness of an attribute value on a given database table.
*
* If a database column is not specified, the attribute will be used.
*
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @return bool
*/
public function validate($attribute, $value, $parameters, $validator)
{
$this->requireParameterCount(3, $parameters, 'unique_custom');
list($connection, $table) = $this->parseTable($parameters[0]);
$input = $validator->getData(); // All attributes
$column = $this->getQueryColumn($parameters, $attribute);
$param1 = explode("=", $parameters[1]);
$value = $input[$param1[0]]; // Set value to attribute value
$exclude = [];
if (isset($parameters[2])) {
$exclude_values = explode("=", $parameters[2]);
$exclude_value = @$input[$exclude_values[0]];
if (!is_null($exclude_value)) {
$exclude_id = $exclude_values[0];
$exclude_value = $input[$exclude_values[0]];
if (!is_null($exclude_value)) {
$exclude[$exclude_values[0]] = $exclude_value;
}
}
}
$query = DB::table("$table")->where($column, '=', $value);
foreach ($exclude as $key => $value) {
$query->where(function ($query) use ($key, $value) {
$query->where($key, '!=', $value);
});
}
$validator->setCustomMessages($this->custom_messages);
return $query->count() == 0;
}
}
I did try and simply append my method to the existing unique method, but as they are in different class spaces, it was causing issues with Laravel's native methods:
use ValidatesAttributes;
$this->validateUnique($attribute, $value, $parameters);