-
Notifications
You must be signed in to change notification settings - Fork 76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Proposal] add newOrFail(), createOrFail() and updateOrFail() methods #179
Comments
Hey, thanks for the suggestions. I don't mind the idea of adding Open to pull requests for the functionality, or I'll have a crack at it when I've got some free time. |
I almost agree. I can imagine that there are times that a developer does want to new up an instance and immediately validate it (and throw an exception if that fails) before continuing to do stuff with that instance. In any case, why not give developers more options anyway? If a developer thinks newing up an instance shouldn't fail then they'll just use the normal construction method. By the way, I already made my own trait which extends yours, so you can copy-paste that code if you want: namespace App\Validation;
/**
* @mixin \Eloquent
*/
trait ValidatingTrait
{
use \Watson\Validating\ValidatingTrait;
/**
* @param array $attributes
* @return static
*/
public static function newOrFail(array $attributes = [])
{
$model = new static($attributes);
$model->isValidOrFail();
return $model;
}
/**
* @param array $attributes
* @param array $options
* @return static
*/
public static function createOrFail(array $attributes = [], array $options = [])
{
$model = static::newOrFail($attributes);
$model->save($options);
return $model;
}
/**
* @param array $attributes
* @return static
*/
public static function firstOrNewOrFail(array $attributes = [])
{
$model = static::firstOrNew($attributes);
if (!$model->exists) $model->isValidOrFail();
return $model;
}
/**
* @param array $attributes
* @param array $options
* @return static
*/
public static function firstOrCreateOrFail(array $attributes = [], array $options = [])
{
$model = static::firstOrNewOrFail($attributes);
$model->save($options);
return $model;
}
/**
* @param array $attributes
* @param array $options
* @return $this
*/
public function updateOrFail(array $attributes = [], array $options = [])
{
$this->fill($attributes)->saveOrFail($options);
return $this;
}
} |
It would be nice if I could do the following with my models that use the
ValidatingTrait
:Which would then be equivalent to:
And just to be complete, this:
would be equivalent to:
The text was updated successfully, but these errors were encountered: