4

This works

'expected_at' => 'date|after:"2016-04-09 10:48:11"',

And this works

$rules['expected_at'] = 'date|after:'.$opportunity->created_at;

This does not work

'expected_at' => 'date|after:created_at',

The "created_at" value in the database is exactly the following

2016-04-09 10:48:11

Note the form is passing the expected_at date to the validator in the following format

2016-04-09

I assume that this means you cannot directly reference a model field in a validator?

mwafi
  • 3,946
  • 8
  • 56
  • 83
Matthew Malone
  • 463
  • 1
  • 9
  • 26
  • Have you installed the very latest version of Laravel using composer update? there have been recent updates to the after function as seen here: https://github.com/laravel/framework/blame/5.2/src/Illuminate/Validation/Validator.php – Dan H Apr 21 '16 at 13:01

3 Answers3

5

In the laravel docs for 5.3 (the version I tested):

Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

https://laravel.com/docs/5.3/validation#rule-after

The string following the "after" rule (start_date in this case) is not a database field, but part of the input string passed to your validator.

So, following what you were attempting to do above, the validator was expecting a field named "created_at" to be passed along with the rest of your submitted input, which likely didn't exist since your intent was to have it read from your model, which would cause it to fail.

Long story short, your last statement was correct. The "before/after" rules do not reference model fields, but rather other input fields passed to the validator, OR date strings that can be interpreted by "strtotime"

Community
  • 1
  • 1
3

This can be validated as:

'expected_at'  => 'required|before:' . date('Y-m-d') . '|date_format:Y-m-d',

You can even pass validator a date argument and compare at the time of validation. I assume, you are searching for date_format validator.

tnchalise
  • 1,573
  • 2
  • 18
  • 38
  • No this is not what I am asking, the date format translates fine. The problem is Laravel cannot reference a field in the model using the validator syntax - you have to have it as $opportunity->created_at; – Matthew Malone Apr 23 '16 at 00:55
1

Agree with @Gordon, and you can try this, without format in FormRequest:

'expected_at' => "date|after:{$this->user()->created_at}",

Note: The reason of non-ability to refer to DB value is because no defined model to use in this stage.

mwafi
  • 3,946
  • 8
  • 56
  • 83