When performing array validations in Laravel with unique rules, Laravel validates one record at a time, causing an N+1 query problem. This is a common issue when importing data from an Excel file and validating it before inserting it into the database. This package solves the problem by batching the unique validations and using whereIn to prevent the N+1 problem.
composer require dazza-dev/laravel-batch-validation
This package is easy to use. Here's an example of how to apply it:
use Illuminate\Support\Facades\Validator;
$data = [
['name' => 'User 1', 'email' => '[email protected]'],
['name' => 'User 2', 'email' => '[email protected]'],
['name' => 'User 3', 'email' => '[email protected]'],
];
// Validator Instance
$validator = Validator::make($data, [
'*.name' => 'required',
'*.email' => 'email:strict|unique:contacts,email',
]);
// Validate in Batches (this prevent n+1 problem)
$validator->validateInBatches();
// Validation fails
if ($validator->fails()) {
throw new \Exception(json_encode($validator->errors()->messages()));
}
You can change the batch size by passing the batchSize
parameter to the validateInBatches
method. The default batch size is 10.
$validator->validateInBatches(batchSize: 20);
This package also supports database rules like unique
, exists
.
$validator = Validator::make($data, [
'*.name' => 'required',
'*.email' => 'email:strict|unique:contacts,email',
]);
You can use the validateInBatches
method in a form request.
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Validator;
class StoreContactRequest extends FormRequest
{
public function rules(): array
{
return [
'*.name' => 'required',
'*.email' => 'email:strict|unique:contacts,email',
];
}
public function withValidator(Validator $validator)
{
if (method_exists($validator, 'validateInBatches')) {
$validator->validateInBatches(batchSize: 100);
}
}
}
Contributions are welcome. If you find any bugs or have ideas for improvements, please open an issue or send a pull request. Make sure to follow the contribution guidelines.
Laravel Batch Validation was created by DAZZA.
This project is licensed under the MIT License.