AlighaThor's avatar

Created and Updated events are both fired for Model::create()

Hi everyone. I have a simple test case with PHPUnit as following in Laravel 5.8.11:

public function test_create_root_category()
{
    Category::create([
        'name' => 'Root category',
        'slug' => 'root-category',
        'category_id' => null
    ]);

    $this->assertDatabaseHas('categories', [
        'name' => 'Root category',
        'category_id' => null
    ]);
}

The problem I'm facing is that I'm trying to listen for proper dispatched events like "created" or "updated" in a EventObserver, but I found that both of them (created/updated) are fired when using Category::create().

In my EventObserver for Category:

    public function created(Category $category)
    {
        dump('Created'); //This is fine.
    }

    public function updated(Category $category)
    {
        dump('Updated'); //This should not be executed.
    }

My output:

Testing started at 12:51 ...
/usr/local/bin/php /home/alighathor/Documentos/Desarrollo/Ardicometal/ardicometal/vendor/phpunit/phpunit/phpunit --configuration /home/alighathor/Documentos/Desarrollo/Ardicometal/ardicometal/phpunit.xml --teamcity
PHPUnit 7.5.8 by Sebastian Bergmann and contributors.

"Updated"
"Created"


Time: 324 ms, Memory: 16.00 MB

OK (1 test, 1 assertion)

Process finished with exit code 0

Does updated() event should not be fired only for the update() method? I'm confused.

Thanks in advance.

0 likes
3 replies
Talinon's avatar
Talinon
Best Answer
Level 51

Are you certain that Category::create() is causing both to fire? I find it especially strange that updated would be called before created. I suspect something in your test set up might be triggering an update on another model that is being observed elsewhere. Try dumping $category and confirm?

 public function updated(Category $category)
    {
        dump($category); //This should not be executed.
    }
1 like
AlighaThor's avatar

@TALINON - Hi Talinon, thanks for the fast reply.

You were right, and I found my issue. I forgot to show this in my previous post in the created() listener:

public function created(Category $category)
{
    $category->category_path = $category->generate_path();
    $category->save();

    dump('Created');
}

Save() is naturally firing updated() too, so, my mistake.

Thanks!

Jaytee's avatar

Yeah so the way it works is that the save method checks to see if the model should be created or updated (based on whether the model already exists etc), and then fire the respective event. I don't believe it fires both, it should fire one or the other.

1 like

Please or to participate in this conversation.