Digging Deeper

Hooks

Hooks are designed to let you the ability to react on model's lifecycle of your models.

Hooks are designed in two ways: one on the controller (around HTTP endpoints) and one on the resource (around model lifecycle events).

Controller Hooks

On your rest controller you can react to every endpoint. Hooks are defined as protected methods and receive the current request as their only argument.

HookFires
beforeDetailsBefore the details endpoint response
beforeSearchBefore the search query runs
afterSearchAfter the search results are built
beforeMutateBefore any mutate operations run
afterMutateAfter all mutate operations complete
beforeOperateBefore an action is dispatched
afterOperateAfter an action completes
beforeDestroyBefore models are deleted
afterDestroyAfter models are deleted
beforeForceDestroyBefore models are force-deleted
afterForceDestroyAfter models are force-deleted
beforeRestoreBefore soft-deleted models are restored
afterRestoreAfter soft-deleted models are restored
class UsersController extends RestController
{
    public static $resource = App\Rest\Resources\UserResource::class;

    protected function beforeSearch(SearchRequest $request): void
    {
        // Runs before the search query executes
    }

    protected function afterMutate(MutateRequest $request): void
    {
        // Runs after all mutate operations complete
    }
}

Resource Hooks

On your resource, you can listen to model lifecycle events. These hooks fire for every part of the API, including nested relation operations.

HookFires
mutatingBefore a model is created or updated
mutatedAfter a model is created or updated
destroyingBefore a model is deleted
destroyedAfter a model is deleted
restoringBefore a soft-deleted model is restored
restoredAfter a soft-deleted model is restored
forceDestroyingBefore a model is force-deleted
forceDestroyedAfter a model is force-deleted
Methods ending with ing fire before the event; methods ending with ed fire after.
class UserResource extends Resource
{
    public function mutated(MutateRequest $request, array $requestBody, Model $model): void
    {
        if ($requestBody['operation'] === 'update') {
            Storage::put('images/avatars/'.$model->getKey().'.jpg', $requestBody['attributes']['file']);
        }
    }
}