Phil
Phil

Reputation: 2246

How are $rules resolved for date variable values

For the following $rules, after:today and after:start_date are resolved as expected. However, I do not understand, how it actually works but… I checked the code, but I can't figure it out. Laravel sends the value following after: through strtotime. Is today a predefined value for strtotime? But start_date is a key in the array I just created. How does that work?

public static $rules = array(
  'name' => 'required', 
  'description' => '', 
  'location' => 'required|alpha-dash', 
  'cost' => 'numeric|min:0', 
  'min_age' => 'numeric|min:0', 
  'max_age' => 'numeric|min:0', 
  'start_date' => 'required|date|after:today', 
  'end_date' => 'required|date|after:start_date', 
  'start_time' => 'required|time', 
  'end_time' => 'required|time', 
  'registration_start_date' => 'date', 
  'registration_end_date' => 'date', 
  'max_attendees'  => 'numeric|min:0'
);

Upvotes: 0

Views: 61

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 153020

Let's start with the validateAfter method in Illuminate\Validation\Validator

protected function validateAfter($attribute, $value, $parameters)
{
    // [unimportant code]

    if ( ! ($date = strtotime($parameters[0])))
    {
        return strtotime($value) > strtotime($this->getValue($parameters[0]));
    }

    return strtotime($value) > $date;
}

First it will check if if the first parameter is a some form of a date. in your case today. If it's not, it will call $this->getValue and use strtotime again. getValue() just returns the value of an attribute by it's name:

protected function getValue($attribute)
{
    if ( ! is_null($value = array_get($this->data, $attribute)))
    {
        return $value;
    }
    elseif ( ! is_null($value = array_get($this->files, $attribute)))
    {
        return $value;
    }
}

Note that this also means any parameter that can be interpreted by strtotime will be used as that. So if you had an attribute named today, not the value of the attribute but rather strtotime('today') would be used for validation

Upvotes: 1

Related Questions