statamic / eloquent-driver

Provides support for storing your Statamic data in a database, rather than flat files.
https://statamic.dev/tips/storing-content-in-a-database
MIT License
104 stars 74 forks source link

EntrySaving called after the model has been saved. #120

Closed addgod closed 1 year ago

addgod commented 1 year ago

The EntrySaving event is called after the entry has been persisted to the database.

So if you in your listener, try to retrieve the original Entry, it will be the new entry, not the old one.

This is what I see

use Statamic\Events\EntrySaving;
use Statamic\Facades\Blink;
use Statamic\Facades\Entry;

class EntrySavingListener
{
    public function handle(EntrySaving $event)
    {
        if ($event->entry->id()) {
            $entry = Entry::find($event->entry->id()); <-- the new entry, not the old
            $original = $entry->model()->getOriginal(); <-- this would be the original, but this does not work with file driven install.
            Blink::put('old::' . $event->entry->id(), $original->toArray());
        }
    }
}

Can anyone else confirm this?

ryanmitchell commented 1 year ago

I think you're hitting up against the blink cache we're using to try and limit the number database queries. If you Blink::forget("eloquent-entry-{$entry->id()}" you should get the old entry.

addgod commented 1 year ago

But the blink cache should not have been set at this time either should it?

ryanmitchell commented 1 year ago

Eloquent driver has a blink cache that it uses to reduce the number of models and database queries. See the entry repository code.

addgod commented 1 year ago

Hmm I dont think this is the case, since even if I do a dd inside the saving listener, then if I refresh the page, then has been updated.

ryanmitchell commented 1 year ago

If i dd() inside your listener (using the same code you provided), then the data is not saved to the database. Once I remove the dd then it works as expected.

Maybe you could take some time and make a sample repository showing your issue so it can be replicated and investigated?