I want to validate two date fields in a form which is from_date and end_date. Need to check from_date is less than end_date.
$rules = array(\'from_date\' => a
Laravel 5:
Here is more extensive approach that follows modern principles and is more Laravel-like. This is a little more complex but still easy to follow and the end results is much cleaner.
Let's start by changing a few things. Let's reduce this to the specific problem, use newer array syntax and apply formatting.
$rules = [
'from_date' => [
'before:'.Input::get('to_date') // This is what we will learn to do
],
'to_date' => [
'after:'.Input::get('from_date') // Do this one on your own
]
];
Now let's create a new Request with php artisan make:request StoreWhateverRequest
. This will create the App/HTTP/Request/StoreWhateverRequest.php
file. Open that and place your rules in the return array of the rules()
function.
return [
'from_date' => 'date',
'to_date' => 'date|after_field:from_date'
];
This will not work yet because after_field
isn't available to use yet. Let's create that. We need a new class that extends validator. You can place it in app/Services
. We need something similar to:
Carbon::parse($this->data[$parameters[0]]);
}
}
In the above we have: $attribute
which is the name of the field we are checking (to_date), $value
is the value of the field we are checking and $parameters
is the parameters we passed to the Validator(from_date) seen in 'to_date' => 'date|afterField:from_date'
. We also need the other data fields passed to the Validator, we can get these with $this->data
. Then we just have to preform the logic appropriately. You really don't even need Carbon here but be sure to parse the string so we don't do string comparison.
Now we need to load this into the application. To do this put the below code inside the boot()
function in app/Providers/AppServiceProviders.php
.
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new afterFieldValidator($translator, $data, $rules, $messages);
});
The final step is easiest. Just inject and instance of StoreWhateverRequest
into our Controller.
...
public function store(StoreWhateverRequest $request)
{
...
All done. I feel this is a pretty SOLID way to solve the problem.