mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
https://www.mongodb.com/docs/drivers/php/laravel-mongodb/
MIT License
7k stars 1.43k forks source link

[Feature Request] $user->getChanges(), date transformation not being applied #3163

Closed masterbater closed 2 weeks ago

masterbater commented 2 weeks ago
 $validatedData = $request->validated();
        $update = $user->update($validatedData);

        return response()->json(['message' => 'success', 'data' => $user->getChanges()], Response::HTTP_OK);

This returns

{"message":"success","data":{"fname":"fname","updatedAt":{"$date":{"$numberLong":"1727594198505"}}}}

I didnt test with default timestamp fields since I have custom fields, but the transformation should work especially with eloquent. Let me const CREATED_AT = 'createdAt'; const UPDATED_AT = 'updatedAt';

GromNaN commented 2 weeks ago

I understand that you expect the field updatedAt to be automatically updated when you call $model->update($data). This field is correctly updated, as proved by this passing test:

    public function testGetChange()
    {
        $user = User::create(['name' => 'John Doe']);
        $user->update(['name' => 'Jane Doe']);
        $this->assertSame(['name', 'updated_at'], array_keys($user->getChanges()));
    }

The call stack to update the timestamp when $user->update() is called:

HasTimestamps.php:64, Illuminate\Database\Eloquent\Model->updateTimestamps()
Model.php:1229, Illuminate\Database\Eloquent\Model->performUpdate()
Model.php:1155, Illuminate\Database\Eloquent\Model->save()
DocumentModel.php:738, MongoDB\Laravel\Tests\Models\User->save()
Model.php:1013, Illuminate\Database\Eloquent\Model->update()

If you freeze the time for testing, using Date::setTestNow(), then updated_at is updated with the non-different value. So $model->getChange() does not detect change on this field.

This is the same behavior with an SQL database. If you think this behavior is problematic, please submit an issue to Laravel.

PHPORM-250

masterbater commented 2 weeks ago

Yes you are right about saving part, but my question is why date transformation or should I say the format of date return by getChanged() doesnt automatically return date or carbon date format. It returns the native date format by mongodb $numberLong

masterbater commented 2 weeks ago

If by default getChanges returns native database changes and doesnt respect your eloquent model casting and attributes mutators then Im wrong here thanks for giving the attention