Skip to content

Latest commit

 

History

History
73 lines (61 loc) · 2.55 KB

File metadata and controls

73 lines (61 loc) · 2.55 KB
description 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.

Hook Fires
beforeDetails Before the details endpoint response
beforeSearch Before the search query runs
afterSearch After the search results are built
beforeMutate Before any mutate operations run
afterMutate After all mutate operations complete
beforeOperate Before an action is dispatched
afterOperate After an action completes
beforeDestroy Before models are deleted
afterDestroy After models are deleted
beforeForceDestroy Before models are force-deleted
afterForceDestroy After models are force-deleted
beforeRestore Before soft-deleted models are restored
afterRestore After 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.

Hook Fires
mutating Before a model is created or updated
mutated After a model is created or updated
destroying Before a model is deleted
destroyed After a model is deleted
restoring Before a soft-deleted model is restored
restored After a soft-deleted model is restored
forceDestroying Before a model is force-deleted
forceDestroyed After a model is force-deleted

:::note 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']);
        }
    }
}