uniqueness_of.php 1006 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php namespace System\Validation\Rules;
  2. use System\DB;
  3. use System\Validation\Rule;
  4. class Uniqueness_Of extends 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 void
  23. */
  24. public function check($attribute, $attributes)
  25. {
  26. if ( ! array_key_exists($attribute, $attributes))
  27. {
  28. return true;
  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. * @param string $table
  40. * @param string $column
  41. * @return Uniqueness_Of
  42. */
  43. public function on($table, $column = null)
  44. {
  45. $this->table = $table;
  46. $this->column = $column;
  47. return $this;
  48. }
  49. }