Resource events
Resources support using events. These events work in a similar way as Laravel model events. You are not required to use resource events over model events, or use them at all. However, they may come in handy when you for example want to access the request data from a form.
Usage
Let's say you have a User resource, you may want to encrypt the users' password when creating the user:
public function creating(Model $model, array $state)
{
$model->password = Hash::make(Str::random());
}
You may need to send a mail after creating an user:
public function created(Model $model, array $state): JsonResponse
{
$this->sendResetLink($model);
return parent::created($model, $state);
}
You will have full control over the retun values of created
and updated
, because these methods by default will send
a JsonResponse.
Available events
You can use any of the following events:
public function retrieved(Model $model)
{
//
}
public function saving(Model $model, ?Model $original = null)
{
//
}
public function saved(Model $model, ?Model $original = null)
{
//
}
public function updating(Model $model, Model $original, array $state)
{
//
}
public function updated(Model $model, Model $original, array $state): JsonResponse
{
//
}
public function creating(Model $model, array $state)
{
//
}
public function created(Model $model, array $state): JsonResponse
{
//
}
public function deleting(Model $model)
{
//
}
public function deleted(Model $model)
{
//
}
public function imported(Model $model): void
{
//
}
public function createdFromDuplicate(Model $created, ?Model $original): void
{
//
}
Form events
You can also override the methods below.
OnFormReady
Will be called every lifecycle, meaning on the initial form request and all subsequent requests.
public function onFormReady(ManagesForm $form): void
{
if ($form->getModel()) {
$form->setSubmitButtonLabel('Update user');
} else {
$form->setSubmitButtonLabel('Create user');
}
}
Duplication
When a resource is created from duplication there will be an event emitted called Qore\System\Events\ResourceCreatedFromDuplicate
.
You can also override the public function createdFromDuplicate(Model $created, ?Model $original): void
inside the resource, to add code that reacts to this event.
Be aware at the definition of the event as the $original
param model that you are duplicating from might have been deleted since the form is started, you should handle this case accordingly.
public function __construct(
public readonly Model $created,
public readonly ?Model $original,
) {
}