Laravel validations
$errorMessage = "NFL Competition already exist for year $this->year and with the selected competition type.";
return [
'name' => 'string',
'abbreviation' => 'required|max:10',
'year' => 'required|digits:4|integer|min:1900|max:' . (date('Y') + 1),
'competition_type_id' => ['required', 'string', new IsCompositeUnique('basketball_competitions', ['year' => $this->year, 'competition_type_id' => $this->competition_type_id], $this->competition_id, $errorMessage)],
];
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;
class IsCompositeUnique implements Rule
{
/**
* @var string
*/
private $tableName;
/**
* @var array
*/
private $compositeColsKeyValue = [];
/**
* @var mixed|null
*/
private $rowId;
private $errorMessage;
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct(string $tableName, array $compositeColsKeyValue, $rowId = null, $errorMessage = null)
{
$this->tableName = $tableName;
$this->compositeColsKeyValue = $compositeColsKeyValue;
$this->rowId = $rowId;
$this->errorMessage = $errorMessage;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value): bool
{
if ($this->rowId) {
$record = DB::table($this->tableName)->where($this->compositeColsKeyValue)->first();
$passess = !$record || ($record && $record->id == $this->rowId);
} else {
$passess = !DB::table($this->tableName)->where($this->compositeColsKeyValue)->exists();
}
return $passess;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message(): string
{
if ($this->errorMessage) {
return $this->errorMessage;
}
$colNames = '';
foreach ($this->compositeColsKeyValue as $col => $value) {
$colNames .= $col . ', ';
}
$colNames = rtrim($colNames, ', ');
return "The combination of $colNames must be unique.";
}
}