Join my Laravel for REST API's course on Udemy 👀

Check if a model was destroyed in a Laravel unit test

April 28, 2022  ‐ 1 min read

Just like testing whether a model was created in some cases you might want to validate whether a model was destroyed after an action. You might test for this after calling a destroy() endpoint of an JSON API for example.

Laravel has a convenient database assertion method in its unit testing library to help you with this; namely the assertModelMissing() method.

Under the hood the assertModelMissing() assertion method calls the assertDatabaseHas() method to validate whether the primary key of the model passed as an argument is missing in the database.

<?php

namespace Tests\Feature\Controllers\PageController;

use App\Models\Page;
use Tests\TestCase;

class PageControllerDestroyTest extends TestCase
{
    public function it_can_destroy_a_page()
    {
        // Setup the models we need using test factories
        $user = User::factory()->create();
        $page = Page::factory()->create(['user_id' => $user->id]);

        // Make the request
        $token = $user->createToken('test')->plainTextToken;
        $response = $this->withToken($token)->deleteJson(route('pages.destroy', [$page->id]));

        // Make our assertions
        $response->assertStatus(204);
        $this->assertModelMissing($page);
    }
}