try {
$user = User::create(request()->all());
} catch (HnhDigital\ModelSchema\Exceptions\ValidationException $exception) {
// Do something about the validation.
// You can add things to the validator.
$exception->getValidator()->errors()->add('field', 'Something is wrong with this field!');
// We've implemented a response.
// This redirects the same as a validator with errors.
return $exception->getResponse('user::add');
}
trait ModelCastAsMoneyTrait
{
/**
* Cast value as Money.
*
* @param mixed $value
*
* @return Money
*/
protected function castAsMoney($value, $currency = 'USD', $locale = 'en_US'): Money
{
return new Money($value, $currency, $locale);
}
/**
* Convert the Money value back to a storable type.
*
* @return int
*/
protected function castMoneyToInt($key, $value): int
{
if (is_object($value)) {
return (int) $value->amount();
}
return (int) $value->amount();
}
/**
* Register the casting definitions.
*/
public static function bootModelCastAsMoneyTrait()
{
static::registerCastFromDatabase('money', 'castAsMoney');
static::registerCastToDatabase('money', 'castMoneyToInt');
static::registerCastValidator('money', 'int');
}
}