Last active
March 12, 2023 14:50
-
-
Save bobbybouwmann/846f3a1163ffc008047c to your computer and use it in GitHub Desktop.
Laravel Custom Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'providers' => [ | |
// other providers | |
// Add the new provider at the bottom | |
'App\Services\Validation\ValidationServiceProvider', | |
], |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Services\Validation; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Validation\Validator; | |
class CustomValidation extends Validator { | |
public function validateSumValues($attribute, $value, $parameters) | |
{ | |
$sum = 0; | |
foreach($parameters as $param) { | |
$sum += Request::get($param); | |
} | |
return ($sum == $value); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$rules = [ | |
'total' => 'sum_values:field1,field2', | |
]; | |
$rules = [ | |
'total' => 'sum_values:field1,field2,field3,field4', | |
]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Services\Validation; | |
use Illuminate\Support\ServiceProvider; | |
class ValidationServiceProvider extends ServiceProvider { | |
/** | |
* Register the service provider. | |
* | |
* @return void | |
*/ | |
public function register() | |
{ | |
} | |
/** | |
* Boot the service provider. | |
*/ | |
public function boot() | |
{ | |
$this->app->validator->resolver(function ($translator, $data, $rules, $messages) | |
{ | |
return new CustomValidation($translator, $data, $rules, $messages); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So the
sum_values
validation is working only thesame
validation is not working?You can easily check if these two fields are the same or not by doing this
If they are the same they should match!