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);
});
}
}
@AtomicRSA
Copy link

Hi Bobby

I have added all the code as above but I am struggling to make it work, this is what I did:
I have 5 fields:
sec_discount - the other 4 must be equal to this one
vip_discount
rec_discount
ref_discount
cus_discount

In my request file I added this two lines:
'total' => 'sum_values:vip_discount,rec_discount,ref_discount,cus_discount', - (to get the value of the 4 fields)
'sec_discount' => 'required|numeric|same:total', - (to check that the two are the same)

It keeps giving error 'The sec discount and total must match' even if they do match.

@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