Laravel nova metrics returns model instance which conflicts the observer
A Laravel eloquent model Car with details id, name, description and user_id has a relation owner() which return a User model. The name and description fields of Car model is encrypted using a unique key belongs to the owner, which is done using a create/update event observer. The key is related to the owner using a relation encryptionKey(). There is no default decryption method added for the model and hence the query response fields will be always encrypted because the decryption is handled in frontend separately. The relation is also has an attribute to get the key along with the user model using below method.
public function getEncryptionKeyAttribute()
{
return $this->owner->encryptionKey; // or $this->owner()->encryptionKey()
}
I've added laravel nova resources for both models. The encrypted fields will be decrypted using an observer during the Nova:serving event which is added in NovaServiceProvider boot() method. The decrypt function accesses owner data because the fields are encrypted using owner encryption key.
I've also added a metrics CarsPerDay with the calculate method as given below.
public function calculate(NovaRequest $request)
{
return $this->countByDays($request, Car::class);
}
But when the dashboard doesn't load the metrics instead it throws error Trying to get property 'encryptionKey' of non-object. I dumped the model data in the decryption method, but it doens't seems like a valid model data. It does not contains any fields of the original db table, instead it only contains the fields date_result and aggregate columns which are created by some method in metric generation. But the response data is of type Car model even though the fields are invalid. Hence the $car->owner() returns null and the attribute encryptionKey resulted the above mentioned error in dashboard because the attribute tries the relation on null.
So what I understand is that Nova tries to calculate the aggregate for the metrics which returns the type Car model. Because the response is a Car model, the observer tries to decrypt the encrypted data using owner encryption key, but the owner() relation is null for the response data. I just wonder how can I solve the issue. I hope to fix the metrics calculation response instead of changing the existing implementation of the system.
Please or to participate in this conversation.