Dwight Watson's blog

Asserting that an Eloquent model soft deletes

This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.

Ran into an unpleasant situation recently where I discovered a model that I thought was soft-deleting wasn't actually - database records were actually being removed. This meant that a few months of reporting data were thrown off completely and a lot of content was lost forever.

In addition to adding the SoftDeletes trait back to the model I also added tests to ensure this didn't happen again. Here's a small PHPUnit helper that might help you do the same.

/**
* Assert that the given class soft deletes.
*
* @param string $model
* @return void
*/
public function assertSoftDeletes(string $model)
{
$instance = new $model;

$this->assertUsesTrait(Illuminate\Database\Eloquent\SoftDeletes::class, $instance);
$this->assertContains('deleted_at', $instance->getDates());
}

/**
* Assert that the given class uses the provided trait name.
*
* @param string $trait
* @param mixed $class
* @return void
*/
public function assertUsesTrait($trait, $class)
{
$this->assertContains($trait, class_uses($class));
}

It's easy to use, just pass the model's class name and you should be good to go.

/** @test */
function it_soft_deletes()
{
$this->assertSoftDeletes(User::class);
}

A blog about Laravel & Rails by Dwight Watson;

Picture of Dwight Watson

Follow me on Twitter, or GitHub.