I'm trying to push all the model changes to the frontend using updated event. I don't want to send the whole model so I found the hasChanges()
method. But it's always empty.
My first thought was that this event fires BEFORE the actual save but getDirty()
is also empty. Then I thought in debug bar that for some reason it's retrieving the model once again (selecting from DB) right after updating it. Is this normal behaviour or is it just creating a new model object and not passing the existing one to the event?
Event:
class IcUpdated implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
private $ic;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($ic)
{
$this->ic = $ic;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return [
new Channel('dashboard_' . ConfigHelper::getSelectedOrganizationId())
];
}
public function broadcastAs()
{
return 'ic.updated';
}
public function broadcastWith()
{
return $this->ic->getChanges();
}
}
Model:
protected $dispatchesEvents = [
'updated' => \App\Events\IcUpdated::class,
];
So how would I access and send only changed fields in event?
This is caused by the SerializesModels trait. This causes the model to be serialized to its primary key and then refetched from the database when the job is executed.
This is useful for cases where there is a delay on a queued job, for instance, you queue an email to go out to $user. The user changes their email address, the queued job runs but goes out to the new email address since it refetches the user from the database.
In your case, you definitely don't want to serialize the model to its key since you need properties stored in that specific model instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With