Laravel 5:
Here is a more extensive approach that follows modern principles and is more similar to Laravel. It's a little trickier, but still easy to follow, and the end results are much cleaner.
Let's start by changing a few things. Let me reduce this to a specific problem, use the new 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 create a new request with php artisan make:request StoreWhateverRequest . This will create the file App/HTTP/Request/StoreWhateverRequest.php . Open it and put your rules in the returned array of the rules() function.
return [ 'from_date' => 'date', 'to_date' => 'date|after_field:from_date' ];
This will not work yet, because after_field is not yet available. Let me create it. We need a new class that extends the validator. You can put it in app/Services . We need something similar:
<?php namespace App\Services; use Illuminate\Validation\Validator; use Carbon\Carbon; class AfterFieldValidator extends Validator { public function validateAfterField($attribute, $value, $parameters) { return Carbon::parse($value) > Carbon::parse($this->data[$parameters[0]]); } }
In the above example, 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 are the parameters that we passed to Validator (from_date) in 'to_date' => 'date|afterField:from_date' . We also need other data fields passed to Validator, we can get them using $this->data . Then we just need to pre-form the logic. You really don't need Carbon here, but be sure to parse the string so that we don't compare the strings.
Now we need to download this application. To do this, enter the boot() code below in app/Providers/AppServiceProviders.php .
Validator::resolver(function($translator, $data, $rules, $messages) { return new afterFieldValidator($translator, $data, $rules, $messages); });
The last step is the easiest. Just enter and enter StoreWhateverRequest into our controller.
... public function store(StoreWhateverRequest $request) { ...
Done. I feel this is a pretty solid way to solve the problem.