Skip to content

Instantly share code, notes, and snippets.

@martinbean
Last active July 23, 2018 14:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinbean/b21e6bf5f5d75ffa9244b4bf530ea81e to your computer and use it in GitHub Desktop.
Save martinbean/b21e6bf5f5d75ffa9244b4bf530ea81e to your computer and use it in GitHub Desktop.
Sum (of an array) validation in Laravel
<?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()
{
//
}
}
@martinbean
Copy link
Author

Usage:

'field_name' => 'sum:1'

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).

@legreco
Copy link

legreco commented Jun 13, 2018

Great. Thanks a lot!

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