F
Filament4mo ago
nowak

What is the best way to check if updated resource attributes have changed in afterSave hook?

I am currently doing this, but it seems inefficient and too verbose:
protected function afterSave(): void
{
$mealType = $this->record;
$request = request()->all();
$originalOrderDeadline = null;
$updatedOrderDeadline = null;

// Decode the JSON snapshot
if (isset($request['components'][0]['snapshot'])) {
$snapshot = json_decode($request['components'][0]['snapshot'], true);

if (isset($snapshot['data']['data'])) {
foreach ($snapshot['data']['data'] as $data) {
if (isset($data['id']) && $data['id'] == $mealType->id) {
$originalOrderDeadline = $data['order_deadline'];
break;
}
}
}
}

// Get the updated order_deadline
if (isset($request['components'][0]['updates']['data.order_deadline'])) {
$updatedOrderDeadline = $request['components'][0]['updates']['data.order_deadline'];
}
}
protected function afterSave(): void
{
$mealType = $this->record;
$request = request()->all();
$originalOrderDeadline = null;
$updatedOrderDeadline = null;

// Decode the JSON snapshot
if (isset($request['components'][0]['snapshot'])) {
$snapshot = json_decode($request['components'][0]['snapshot'], true);

if (isset($snapshot['data']['data'])) {
foreach ($snapshot['data']['data'] as $data) {
if (isset($data['id']) && $data['id'] == $mealType->id) {
$originalOrderDeadline = $data['order_deadline'];
break;
}
}
}
}

// Get the updated order_deadline
if (isset($request['components'][0]['updates']['data.order_deadline'])) {
$updatedOrderDeadline = $request['components'][0]['updates']['data.order_deadline'];
}
}
2 Replies
LeandroFerreira
LeandroFerreira4mo ago
what about wasChanged? Maybe this can help you.. https://laravel.com/docs/11.x/eloquent#examining-attribute-changes
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
nowak
nowakOP4mo ago
Ahh! I only tried isDirty, will try with wasChanged!
Want results from more Discord servers?
Add your server