Skip to content

Instantly share code, notes, and snippets.

@bobbybouwmann
Last active March 12, 2023 14:50
Show Gist options
  • Save bobbybouwmann/846f3a1163ffc008047c to your computer and use it in GitHub Desktop.
Save bobbybouwmann/846f3a1163ffc008047c to your computer and use it in GitHub Desktop.
Laravel Custom Validation
'providers' => [
// other providers
// Add the new provider at the bottom
'App\Services\Validation\ValidationServiceProvider',
],
<?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);
}
}
$rules = [
'total' => 'sum_values:field1,field2',
];
$rules = [
'total' => 'sum_values:field1,field2,field3,field4',
];
<?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);
});
}
}
@bobbybouwmann
Copy link
Author

So the sum_values validation is working only the same validation is not working?

You can easily check if these two fields are the same or not by doing this

dd(Request::get('total'), Request::get('sec_discount'));

If they are the same they should match!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment