Skip to content

Instantly share code, notes, and snippets.

@mabasic
Last active December 20, 2019 02:48
Show Gist options
  • Save mabasic/8cf7f1a895218ca466d9 to your computer and use it in GitHub Desktop.
Save mabasic/8cf7f1a895218ca466d9 to your computer and use it in GitHub Desktop.
Custom Array Validation for Laravel
<?php
class ArrayValidation extends Illuminate\Validation\Validator
{
public function validatePeriodArray($field, $values, $params)
{
$valid = true;
foreach($values as $value)
{
$validator = Validator::make(
array('period' => $value),
array('period' => array('required', 'date_format:d-m-Y - d-m-Y'))
);
if ($validator->fails())
{
$valid = false;
break;
}
}
if($valid)
{
return true;
}
else
{
return false;
}
}
public function validatePricePerDayArray($field, $values, $params)
{
$valid = true;
foreach($values as $value)
{
$validator = Validator::make(
array('price_per_day' => $value),
array('price_per_day' => array('required', 'numeric', 'min:0'))
);
if ($validator->fails())
{
$valid = false;
break;
}
}
if($valid)
{
return true;
}
else
{
return false;
}
}
}
<?php
//... other stuff
/*
ArrayValidation class that extends Validation class
*/
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new ArrayValidation($translator, $data, $rules, $messages);
});
'required_with:rent|array|pricePerDayArray', 'period' => 'required_with:price_per_day|array|periodArray' ); ```
@mdurao
Copy link

mdurao commented Sep 12, 2014

Thank you, can you check my second question in laracasts forum? tia.

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