-
-
Save mohamedsabil83/b426bf3c4a0ef7c97638abfa7954eaf2 to your computer and use it in GitHub Desktop.
A Rule to validate the uniqueness of json translated fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Rules; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Contracts\Validation\Rule; | |
class UniqueJsonRule implements Rule | |
{ | |
protected ?string $ignoreColumn = null; | |
protected ?string $ignoreValue = null; | |
/** | |
* Create a new rule instance. | |
* | |
* @return void | |
*/ | |
public function __construct( | |
public string $table, | |
public ?string $column = null, | |
public string $locale = 'en', | |
) {} | |
/** | |
* Create a new rule instance. | |
* | |
* @param string $table | |
* @param string|null $column | |
* | |
* @return static | |
*/ | |
public static function for(string $table, ?string $column = null, ?string $locale = 'en') | |
{ | |
return new static($table, $column, $locale); | |
} | |
/** | |
* Determine if the validation rule passes. | |
* | |
* @param string $attribute | |
* @param mixed $value | |
* @return bool | |
*/ | |
public function passes($attribute, $value) | |
{ | |
$query = DB::table("{$this->table}")->where("{$this->column}->{$this->locale}", $value); | |
if ($this->ignoreColumn) { | |
$query->where("{$this->ignoreColumn}", "!=", $this->ignoreValue); | |
} | |
return $query->count() === 0; | |
} | |
/** | |
* Get the validation error message. | |
* | |
* @return string | |
*/ | |
public function message() | |
{ | |
return "The {$this->column} has already been taken."; | |
} | |
public function ignore($value, string $column = 'id') | |
{ | |
$this->ignoreValue = $value; | |
$this->ignoreColumn = $column; | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment