You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

70 lines
1.5 KiB

<?php
namespace App\Rules;
use Illuminate\Contracts\Database\Query\Builder;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;
class UniqueRule implements Rule
{
private string $table;
private string $field;
private Builder $query;
public function __construct(string $table, string $field)
{
$this->table = $table;
$this->field = $field;
$this->query = DB::table($this->table);
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
* @throws \Throwable
*/
public function passes($attribute, $value)
{
throw_if(is_array($value), 'UniqueRule won\'t work in array values like ' . $attribute);
return empty($value) ? true : !$this->query->where($this->field, $value)->exists();
}
public function withoutTrashed($deletedAtColumn = 'deleted_at'): UniqueRule
{
$this->query->whereNull($deletedAtColumn);
return $this;
}
public function where($column, $value): UniqueRule
{
$this->query->where($column, $value);
return $this;
}
public function ignore($id): UniqueRule
{
if (empty($id)) {
return $this;
}
$this->query->whereNot('id', $id);
return $this;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'select value already exists.';
}
}