AlighaThor
7 months ago

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

Posted 7 months ago by AlighaThor

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.

Please sign in or create an account to participate in this conversation.