zerociudo
zerociudo

Reputation: 377

Eloquent update and event observers

I am making an API with lumen. I am trying to update entry and fire updated observer. What I tried so far

$data = [];
$fota_device = Fota_device::find($deviceId);
$fota_device->update($data);

This code does not update database or fire updated event.

$data = [];
$fota_device = Fota_device::where('id', $deviceId);
$fota_device->update($data);

This code updates database but also does not fire the event. I have read that eloquent does not fire updated events on mass assigns, but one of this way should at least fire the event but does not.

my observer

public function updated(Device $device)
{
    dd($fota_device);
    $user = Auth::user();
    $action = Users_action::create([
        'userId' => $user->id, 
        'created_at' => \Carbon\Carbon::now()->toDateTimeString()
    ]);
}

Why does first code sample not update the entry in the table and why could the observer not be fired?

Upvotes: 0

Views: 3384

Answers (1)

vpalade
vpalade

Reputation: 1437

On update, it triggers only: saving, saved when it didn't modify anything;

This will NOT fire the update event because it's a mass update:

$fota_device = Fota_device::where('id', $deviceId)->update(['fieldName' => $value]);

This will fire the update event if $value differ from the value from database:

User::find($id)->update(['fieldName' => $value]);

In your case, $data = []; is empty array and it didn't modify (update) anything;

Upvotes: 3

Related Questions