uniqueness_of.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php namespace System\Validation\Rules;
  2. use System\DB;
  3. use System\Validation\Nullable_Rule;
  4. class Uniqueness_Of extends Nullable_Rule {
  5. /**
  6. * The database table that should be checked.
  7. *
  8. * @var string
  9. */
  10. public $table;
  11. /**
  12. * The database column that should be checked.
  13. *
  14. * @var string
  15. */
  16. public $column;
  17. /**
  18. * Evaluate the validity of an attribute.
  19. *
  20. * @param string $attribute
  21. * @param array $attributes
  22. * @return bool
  23. */
  24. public function check($attribute, $attributes)
  25. {
  26. if ( ! is_null($nullable = parent::check($attribute, $attributes)))
  27. {
  28. return $nullable;
  29. }
  30. if (is_null($this->column))
  31. {
  32. $this->column = $attribute;
  33. }
  34. return DB::table($this->table)->where($this->column, '=', $attributes[$attribute])->count() == 0;
  35. }
  36. /**
  37. * Set the database table and column.
  38. *
  39. * The attribute name will be used as the column name if no other
  40. * column name is specified.
  41. *
  42. * @param string $table
  43. * @param string $column
  44. * @return Uniqueness_Of
  45. */
  46. public function on($table, $column = null)
  47. {
  48. $this->table = $table;
  49. $this->column = $column;
  50. return $this;
  51. }
  52. }