mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Home Page:https://www.mongodb.com/compatibility/mongodb-laravel-integration

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Fatal casting issues

stubbo opened this issue · comments

  • Laravel-mongodb Version: >= 4.1.0
  • PHP Version: Any (I'm using 8.2.14)
  • Database Driver & Version: Any (I'm using MongoDB, server: 6.0.6, PHP driver: 1.16.2)

Description:

Models sometimes fail to set attributes because the MongoDB\Laravel\Eloquent\Model::setAttribute calls castAttribute, which is intended to be called when going from database to PHP and not PHP to database.

The main cast which has this issue is any of the encryption ones, the model will attempt to decrypt something which isn't encrypted.

I have started work on a PR to fix this, hopefully I can get it finished today/tomorrow.

Steps to reproduce

  1. Create a model with an encrypted cast
class EncryptedModel extends \MongoDB\Laravel\Eloquent\Model {
    public $fillable = ['fieldName'];
    public $casts = ['fieldName' => 'encrypted'];
}
  1. Try to set the encrypted value, this is when it should error with: Illuminate\Contracts\Encryption\DecryptException: The payload is invalid.
EncryptedModel::make(['fieldName' => 'willError']);
  1. 😭

Expected behaviour

The value should be set without error.
$model->fieldName should return a decrypted string.
$model->getRawOriginal('fieldName') should return an encrypted string.

Actual behaviour

Anything which calls setAttribute will error which includes calls to: make, create, update
Here is a working test which shows this issue: https://github.com/stubbo/laravel-mongodb/actions/runs/7462021749

Hit this issue today when switching a Laravel project from jenssegers/mongodb to mongodb/laravel-mongodb.
Showstopping error; had to switch back.