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 around the resource and one on the controller.
On your rest controller you are able to listen to every endpoint such as: beforeDetails
, beforeSearch
, afterSearch
, beforeMutate
, afterMutate
, beforeOperate
, afterOperate
, beforeDestroy
, afterDestroy
, beforeForceDestroy
and afterForceDestroy
.
class UsersController extends RestController
{
public static $resource = App\Rest\Resources\UserResource::class;
/**
* Executed before details.
*
* @param DetailsRequest $request
*
* @return void
*/
protected function beforeDetails(DetailsRequest $request): void
{
//
}
}
On your resource, you are able to listen to every lifecycle events. This happens in every part of the API even on relations.
Laravel Rest Api offers you methods such as: mutating
, mutated
, destroying
, destroyed
, restoring
, restored
, forceDestroying
and forceDestroyed
.
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'])
}
}
}
::callout{icon="i-heroicons-light-bulb" color="blue"} Methods ending with "ing" happens before the event, those with "ed" after. ::