Skip to content

Instantly share code, notes, and snippets.

@sonOfRa
Created September 28, 2017 14:23
Show Gist options
  • Select an option

  • Save sonOfRa/89f6d24aa86b6b214d0fd9bdcb246f4d to your computer and use it in GitHub Desktop.

Select an option

Save sonOfRa/89f6d24aa86b6b214d0fd9bdcb246f4d to your computer and use it in GitHub Desktop.
<?php
namespace App\Rules;
use App\Entry;
use Illuminate\Contracts\Validation\Rule;
/**
* Class UniqueCategoryId
*
* Rule to verify whether an in-category-id is unique, that is, it fulfills the following requirements:
*
* No entry with the same category and in-category-id exists, unless they have sub-ids that are different from each
* other. One entry having a sub-id and the other NOT having a sub-id counts as the sub-ids being different.
* @package App\Rules
*/
class UniqueCategoryId implements Rule
{
/**
* @var int
*/
private $category;
/**
* @var int
*/
private $except;
/**
* @var string
*/
private $subid;
/**
* Create a new rule instance.
*
* @param int $category the category in which this ID should be unique
* @param string $subid the sub-id used for this entry
* @param int $except entries to exempt from the uniqueness check (for updating instead of creating)
*/
public function __construct(int $category, ?string $subid, int $except = null)
{
$this->category = $category;
$this->except = $except;
$this->subid = $subid;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$entries = Entry::whereInCategoryId($value)
->whereInCategorySubId($this->subid)
->whereCategoryId($this->category)->get();
foreach($entries as $entry) {
if ($entry->id !== $this->except) {
/*
* The entry we're looking at has the same sub-id as the newly submitted/updated entry,
* and is not exempted. The validation fails.
*/
return false;
}
}
return true;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The category-id must be unique within this category, unless a different sub-id is set.';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment