Thursday, April 13, 2017

How to avoid serialization of foreign model in laravel events?

I have Eloquent model Instance (id - primary key, title - text, location - point), where point is mysql data type.

When I use this model in events which should be broadcasted into user's browser via websockets, I use SerializesModels trait, because otherwise it can not serialize object.

Instance model has this function

public function getLocationAttribute($value) {
    if($value === null) return null;
    $value = unpack('Lpadding/corder/Lgtype/dlatitude/dlongitude', $value);
    return $value['latitude'] . ',' . $value['longitude'];
}

That's why when it uses SerializesModels trait it gets correct value (not binary from column of data type 'POINT').

But when this model is used in relation

InstanceComment
    id - primary key
    user_id - id of user
    text - comment text
    instance - `Instance` (in database it is just an integer, but in php it is actual model).

When I issue

event(new InstanceCommentCreated($instanceComment))

it fails with InvalidPayloadException at Queue.php:89

Because it tries to serialize this object structure

InstanceComment
    id = 1
    user_id = 1
    text = 'hello'
    instance =
        id = 1
        title = 'example instance'
        location = binary data from database (getLocationAttribute() is not used)

What are my options to force serializations in such cases? When Instance is primary object in event SerializesModels trait helps, but when it is foreign model - it does'nt.



via Jackson J

Advertisement