Skip to content

Instantly share code, notes, and snippets.

@martinbean
Last active July 23, 2018 14:23
Show Gist options
  • 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()
{
//
}
}
@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