sigd/app/Rules/UniqueInSchema.php

48 lines
1.1 KiB
PHP

<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\DB;
class UniqueInSchema implements ValidationRule
{
protected $schema;
protected $table;
protected $column;
protected $ignoreId;
public function __construct($schema, $table, $column, $ignoreId = null)
{
$this->schema = $schema;
$this->table = $table;
$this->column = $column;
$this->ignoreId = $ignoreId;
}
public function passes($attribute, $value)
{
$query = DB::table($this->schema . '.' . $this->table)
->where($this->column, $value);
if ($this->ignoreId !== null) {
$query->where('id', '!=', $this->ignoreId);
}
return !$query->exists();
}
public function message()
{
return 'The :attribute has already been taken.';
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (!$this->passes($attribute, $value)) {
$fail($this->message());
}
}
}