I am upgrading my Laravel application from 4 to 5. However, I have a custom validator that I cannot get to work.
In L4, I made a validators.php file and included it in global.php using require app_path().'/validators.php';
.
I tried doing somewhat the same in L5. I dropped a validator in app/Validators/Validators.php, and updated my composer.json.
"files": [
"app/Validators/Validators.php"
]
However, now nothing renders on any page. What've I done wrong?
so here's what I did on adding a custom validation. this is for laravel 5.1
PHP Artisan make:request MyFormValidationRequest
file is created underapp\Requests\MyFormValidationRequest.php
Here's the initial code:
IMPORTANT: Change the return value of
authorize()
method to true, if you're not doing any authentication. it's initial value is false. else you get a white page with a "Forbidden" error message.I added a rule under the function
rules()
, here's what it looks liketoday_onwards
is my new validation.I created a folder named 'Services' under App folder
I created a file named 'ValidatorExtended.php' under App\Services folder , here's the code below:
Note: the validateTodayOnwards method is where you put your logic. the name of the method should always start in "validate" then the name of your new validation key which should be in title case,
Another note your validation key should be separated by underscore and all small letters, in this case, "today_onwards". the underscore should be put before all first capital letters in the method name. I hope I explained it good.
TodayOnwards method is equivalent to validation name of "today_onwards",
another example, if I created validateOldPassword, your validation key should be "old_password".
I added below code in
app\Providers\AppServiceProvider.php
insideboot()
method.Don't forget to add below library, one is the Validator class and the other is your own class which is the "
ValidatorExtended
".Here's what the whole file looks like, [
app\Providers\AppServiceProvider.php
]That's it. done. you created your own custom validation.
Additionally, if you want to use it in your controller, below is the code:
Instead of using Request Class you use your own class which is an extension of the Request class.
Try the following:
Validator
class.ServiceProvider
.config/app.php
file.You can create the bind at
Services
folder like this:Then, use a service provider to extends the core:
Finally, import your service provider at
config/app.php
like so: