Skip to content
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

Before & After commit hooks #12

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 85 additions & 1 deletion src/Http/Controllers/EloquentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,47 @@ protected function hydrate(ResourceInterface $resource, Model $model)
*/
protected function commit(Model $model)
{
return $model->save();
$isUpdating = $model->exists;

$this->beforeCommit($model, $isUpdating);

$result = $model->save();

if ($result) {
$this->afterCommit($model, $isUpdating);
}

return $result;
}

/**
* Determines which callback to use before creating or updating a model.
*
* @param Model $model
* @param bool $isUpdating
*/
protected function beforeCommit(Model $model, $isUpdating)
{
if ($isUpdating) {
$this->updating($model);
} else {
$this->creating($model);
}
}

/**
* Determines which callback to use after a model is updated or created.
*
* @param Model $model
* @param bool $isUpdating
*/
protected function afterCommit(Model $model, $isUpdating)
{
if ($isUpdating) {
$this->updated($model);
} else {
$this->created($model);
}
}

/**
Expand Down Expand Up @@ -350,4 +390,48 @@ private function doDestroy(Model $model)
return $this->destroy($model);
});
}

/**
* Called before the model is created.
*
* Child classes can overload this method if they need to do any logic pre-creation.
*
* @param Model $model
*/
protected function creating(Model $model)
{
}

/**
* Called after the model has been created.
*
* Child classes can overload this method if they need to do any logic post-creation.
*
* @param Model $model
*/
protected function created(Model $model)
{
}

/**
* Called before the model is updated.
*
* Child classes can overload this method if they need to do any logic pre-updating.
*
* @param Model $model
*/
protected function updating(Model $model)
{
}

/**
* Called after the model has been updated.
*
* Child classes can overload this method if they need to do any logic post-updating.
*
* @param Model $model
*/
protected function updated(Model $model)
{
}
}