Last active
July 23, 2018 14:23
-
-
Save martinbean/b21e6bf5f5d75ffa9244b4bf530ea81e to your computer and use it in GitHub Desktop.
Sum (of an array) validation in Laravel
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\Providers; | |
use Illuminate\Support\Facades\Validator; | |
use Illuminate\Support\ServiceProvider; | |
use InvalidArgumentException; | |
class ValidationServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Bootstrap the application services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
Validator::extend('sum', function ($attribute, $value, $parameters) { | |
if (count($parameters) !== 1) { | |
throw new InvalidArgumentException('Validation rule sum requires exactly 1 parameter.'); | |
} | |
return array_sum($value) >= $parameters[0]; | |
}); | |
} | |
/** | |
* Register the application services. | |
* | |
* @return void | |
*/ | |
public function register() | |
{ | |
// | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Validates that the sum of an array is greater than the specified value. Handy for validating an associative array of product IDs and quantities, and ensuring that the sum of quantities is greater than zero (i.e. on a checkout form submission).