Database Testing
- Introduction
- Defining Model Factories
- Creating Models Using Factories
- Factory Relationships
- Running Seeders
- Available Assertions
Introduction
Laravel provides a variety of helpful tools and assertions to make it easier to test your database driven applications. In addition, Laravel model factories and seeders make it painless to create test database records using your application's Eloquent models and relationships. We'll discuss all of these powerful features in the following documentation.
Resetting The Database After Each Test
Before proceeding much further, let's discuss how to reset your database after each of your tests so that data from a previous test does not interfere with subsequent tests. Laravel's included Illuminate\Foundation\Testing\RefreshDatabase
trait will take care of this for you. Simply use the trait on your test class:
1<?php23namespace Tests\Feature;45use Illuminate\Foundation\Testing\RefreshDatabase;6use Illuminate\Foundation\Testing\WithoutMiddleware;7use Tests\TestCase;89class ExampleTest extends TestCase10{11 use RefreshDatabase;1213 /**14 * A basic functional test example.15 *16 * @return void17 */18 public function test_basic_example()19 {20 $response = $this->get('/');2122 // ...23 }24}
1<?php23namespace Tests\Feature;45use Illuminate\Foundation\Testing\RefreshDatabase;6use Illuminate\Foundation\Testing\WithoutMiddleware;7use Tests\TestCase;89class ExampleTest extends TestCase10{11 use RefreshDatabase;1213 /**14 * A basic functional test example.15 *16 * @return void17 */18 public function test_basic_example()19 {20 $response = $this->get('/');2122 // ...23 }24}
Defining Model Factories
Concept Overview
First, let's talk about Eloquent model factories. When testing, you may need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, Laravel allows you to define a set of default attributes for each of your Eloquent models using model factories.
To see an example of how to write a factory, take a look at the database/factories/UserFactory.php
file in your application. This factory is included with all new Laravel applications and contains the following factory definition:
1namespace Database\Factories;23use Illuminate\Database\Eloquent\Factories\Factory;4use Illuminate\Support\Str;56class UserFactory extends Factory7{8 /**9 * Define the model's default state.10 *11 * @return array12 */13 public function definition()14 {15 return [16 'name' => $this->faker->name(),17 'email' => $this->faker->unique()->safeEmail(),18 'email_verified_at' => now(),19 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password20 'remember_token' => Str::random(10),21 ];22 }23}
1namespace Database\Factories;23use Illuminate\Database\Eloquent\Factories\Factory;4use Illuminate\Support\Str;56class UserFactory extends Factory7{8 /**9 * Define the model's default state.10 *11 * @return array12 */13 public function definition()14 {15 return [16 'name' => $this->faker->name(),17 'email' => $this->faker->unique()->safeEmail(),18 'email_verified_at' => now(),19 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password20 'remember_token' => Str::random(10),21 ];22 }23}
As you can see, in their most basic form, factories are classes that extend Laravel's base factory class and define definition
method. The definition
method returns the default set of attribute values that should be applied when creating a model using the factory.
Via the faker
property, factories have access to the Faker PHP library, which allows you to conveniently generate various kinds of random data for testing.
You can set your application's Faker locale by adding a faker_locale
option to your config/app.php
configuration file.
Generating Factories
To create a factory, execute the make:factory
Artisan command:
1php artisan make:factory PostFactory
1php artisan make:factory PostFactory
The new factory class will be placed in your database/factories
directory.
Model & Factory Discovery Conventions
Once you have defined your factories, you may use the static factory
method provided to your models by the Illuminate\Database\Eloquent\Factories\HasFactory
trait in order to instantiate a factory instance for that model.
The HasFactory
trait's factory
method will use conventions to determine the proper factory for the model the trait is assigned to. Specifically, the method will look for a factory in the Database\Factories
namespace that has a class name matching the model name and is suffixed with Factory
. If these conventions do not apply to your particular application or factory, you may overwrite the newFactory
method on your model to return an instance of the model's corresponding factory directly:
1use Database\Factories\Administration\FlightFactory;23/**4 * Create a new factory instance for the model.5 *6 * @return \Illuminate\Database\Eloquent\Factories\Factory7 */8protected static function newFactory()9{10 return FlightFactory::new();11}
1use Database\Factories\Administration\FlightFactory;23/**4 * Create a new factory instance for the model.5 *6 * @return \Illuminate\Database\Eloquent\Factories\Factory7 */8protected static function newFactory()9{10 return FlightFactory::new();11}
Next, define a model
property on the corresponding factory:
1use App\Administration\Flight;2use Illuminate\Database\Eloquent\Factories\Factory;34class FlightFactory extends Factory5{6 /**7 * The name of the factory's corresponding model.8 *9 * @var string10 */11 protected $model = Flight::class;12}
1use App\Administration\Flight;2use Illuminate\Database\Eloquent\Factories\Factory;34class FlightFactory extends Factory5{6 /**7 * The name of the factory's corresponding model.8 *9 * @var string10 */11 protected $model = Flight::class;12}
Factory States
State manipulation methods allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your Database\Factories\UserFactory
factory might contain a suspended
state method that modifies one of its default attribute values.
State transformation methods typically call the state
method provided by Laravel's base factory class. The state
method accepts a closure which will receive the array of raw attributes defined for the factory and should return an array of attributes to modify:
1/**2 * Indicate that the user is suspended.3 *4 * @return \Illuminate\Database\Eloquent\Factories\Factory5 */6public function suspended()7{8 return $this->state(function (array $attributes) {9 return [10 'account_status' => 'suspended',11 ];12 });13}
1/**2 * Indicate that the user is suspended.3 *4 * @return \Illuminate\Database\Eloquent\Factories\Factory5 */6public function suspended()7{8 return $this->state(function (array $attributes) {9 return [10 'account_status' => 'suspended',11 ];12 });13}
Factory Callbacks
Factory callbacks are registered using the afterMaking
and afterCreating
methods and allow you to perform additional tasks after making or creating a model. You should register these callbacks by defining a configure
method on your factory class. This method will be automatically called by Laravel when the factory is instantiated:
1namespace Database\Factories;23use App\Models\User;4use Illuminate\Database\Eloquent\Factories\Factory;5use Illuminate\Support\Str;67class UserFactory extends Factory8{9 /**10 * Configure the model factory.11 *12 * @return $this13 */14 public function configure()15 {16 return $this->afterMaking(function (User $user) {17 //18 })->afterCreating(function (User $user) {19 //20 });21 }2223 // ...24}
1namespace Database\Factories;23use App\Models\User;4use Illuminate\Database\Eloquent\Factories\Factory;5use Illuminate\Support\Str;67class UserFactory extends Factory8{9 /**10 * Configure the model factory.11 *12 * @return $this13 */14 public function configure()15 {16 return $this->afterMaking(function (User $user) {17 //18 })->afterCreating(function (User $user) {19 //20 });21 }2223 // ...24}
Creating Models Using Factories
Instantiating Models
Once you have defined your factories, you may use the static factory
method provided to your models by the Illuminate\Database\Eloquent\Factories\HasFactory
trait in order to instantiate a factory instance for that model. Let's take a look at a few examples of creating models. First, we'll use the make
method to create models without persisting them to the database:
1use App\Models\User;23public function test_models_can_be_instantiated()4{5 $user = User::factory()->make();67 // Use model in tests...8}
1use App\Models\User;23public function test_models_can_be_instantiated()4{5 $user = User::factory()->make();67 // Use model in tests...8}
You may create a collection of many models using the count
method:
1$users = User::factory()->count(3)->make();
1$users = User::factory()->count(3)->make();
Applying States
You may also apply any of your states to the models. If you would like to apply multiple state transformations to the models, you may simply call the state transformation methods directly:
1$users = User::factory()->count(5)->suspended()->make();
1$users = User::factory()->count(5)->suspended()->make();
Overriding Attributes
If you would like to override some of the default values of your models, you may pass an array of values to the make
method. Only the specified attributes will be replaced while the rest of the attributes remain set to their default values as specified by the factory:
1$user = User::factory()->make([2 'name' => 'Abigail Otwell',3]);
1$user = User::factory()->make([2 'name' => 'Abigail Otwell',3]);
Alternatively, the state
method may be called directly on the factory instance to perform an inline state transformation:
1$user = User::factory()->state([2 'name' => 'Abigail Otwell',3])->make();
1$user = User::factory()->state([2 'name' => 'Abigail Otwell',3])->make();
Mass assignment protection is automatically disabled when creating models using factories.
Persisting Models
The create
method instantiates model instances and persists them to the database using Eloquent's save
method:
1use App\Models\User;23public function test_models_can_be_persisted()4{5 // Create a single App\Models\User instance...6 $user = User::factory()->create();78 // Create three App\Models\User instances...9 $users = User::factory()->count(3)->create();1011 // Use model in tests...12}
1use App\Models\User;23public function test_models_can_be_persisted()4{5 // Create a single App\Models\User instance...6 $user = User::factory()->create();78 // Create three App\Models\User instances...9 $users = User::factory()->count(3)->create();1011 // Use model in tests...12}
You may override the factory's default model attributes by passing an array of attributes to the create
method:
1$user = User::factory()->create([2 'name' => 'Abigail',3]);
1$user = User::factory()->create([2 'name' => 'Abigail',3]);
Sequences
Sometimes you may wish to alternate the value of a given model attribute for each created model. You may accomplish this by defining a state transformation as a sequence. For example, you may wish to alternate the value of an admin
column between Y
and N
for each created user:
1use App\Models\User;2use Illuminate\Database\Eloquent\Factories\Sequence;34$users = User::factory()5 ->count(10)6 ->state(new Sequence(7 ['admin' => 'Y'],8 ['admin' => 'N'],9 ))10 ->create();
1use App\Models\User;2use Illuminate\Database\Eloquent\Factories\Sequence;34$users = User::factory()5 ->count(10)6 ->state(new Sequence(7 ['admin' => 'Y'],8 ['admin' => 'N'],9 ))10 ->create();
In this example, five users will be created with an admin
value of Y
and five users will be created with an admin
value of N
.
If necessary, you may include a closure as a sequence value. The closure will be invoked each time the sequence needs a new value:
1$users = User::factory()2 ->count(10)3 ->state(new Sequence(4 fn ($sequence) => ['role' => UserRoles::all()->random()],5 ))6 ->create();
1$users = User::factory()2 ->count(10)3 ->state(new Sequence(4 fn ($sequence) => ['role' => UserRoles::all()->random()],5 ))6 ->create();
Within a sequence closure, you may access the $index
or $count
properties on the sequence instance that is injected into the closure. The $index
property contains the number of iterations through the sequence that have occurred thus far, while the $count
property contains the total number of times the sequence will be invoked:
1$users = User::factory()2 ->count(10)3 ->sequence(fn ($sequence) => ['name' => 'Name '.$sequence->index])4 ->create();
1$users = User::factory()2 ->count(10)3 ->sequence(fn ($sequence) => ['name' => 'Name '.$sequence->index])4 ->create();
Factory Relationships
Has Many Relationships
Next, let's explore building Eloquent model relationships using Laravel's fluent factory methods. First, let's assume our application has an App\Models\User
model and an App\Models\Post
model. Also, let's assume that the User
model defines a hasMany
relationship with Post
. We can create a user that has three posts using the has
method provided by the Laravel's factories. The has
method accepts a factory instance:
1use App\Models\Post;2use App\Models\User;34$user = User::factory()5 ->has(Post::factory()->count(3))6 ->create();
1use App\Models\Post;2use App\Models\User;34$user = User::factory()5 ->has(Post::factory()->count(3))6 ->create();
By convention, when passing a Post
model to the has
method, Laravel will assume that the User
model must have a posts
method that defines the relationship. If necessary, you may explicitly specify the name of the relationship that you would like to manipulate:
1$user = User::factory()2 ->has(Post::factory()->count(3), 'posts')3 ->create();
1$user = User::factory()2 ->has(Post::factory()->count(3), 'posts')3 ->create();
Of course, you may perform state manipulations on the related models. In addition, you may pass a closure based state transformation if your state change requires access to the parent model:
1$user = User::factory()2 ->has(3 Post::factory()4 ->count(3)5 ->state(function (array $attributes, User $user) {6 return ['user_type' => $user->type];7 })8 )9 ->create();
1$user = User::factory()2 ->has(3 Post::factory()4 ->count(3)5 ->state(function (array $attributes, User $user) {6 return ['user_type' => $user->type];7 })8 )9 ->create();
Using Magic Methods
For convenience, you may use Laravel's magic factory relationship methods to build relationships. For example, the following example will use convention to determine that the related models should be created via a posts
relationship method on the User
model:
1$user = User::factory()2 ->hasPosts(3)3 ->create();
1$user = User::factory()2 ->hasPosts(3)3 ->create();
When using magic methods to create factory relationships, you may pass an array of attributes to override on the related models:
1$user = User::factory()2 ->hasPosts(3, [3 'published' => false,4 ])5 ->create();
1$user = User::factory()2 ->hasPosts(3, [3 'published' => false,4 ])5 ->create();
You may provide a closure based state transformation if your state change requires access to the parent model:
1$user = User::factory()2 ->hasPosts(3, function (array $attributes, User $user) {3 return ['user_type' => $user->type];4 })5 ->create();
1$user = User::factory()2 ->hasPosts(3, function (array $attributes, User $user) {3 return ['user_type' => $user->type];4 })5 ->create();
Belongs To Relationships
Now that we have explored how to build "has many" relationships using factories, let's explore the inverse of the relationship. The for
method may be used to define the parent model that factory created models belong to. For example, we can create three App\Models\Post
model instances that belong to a single user:
1use App\Models\Post;2use App\Models\User;34$posts = Post::factory()5 ->count(3)6 ->for(User::factory()->state([7 'name' => 'Jessica Archer',8 ]))9 ->create();
1use App\Models\Post;2use App\Models\User;34$posts = Post::factory()5 ->count(3)6 ->for(User::factory()->state([7 'name' => 'Jessica Archer',8 ]))9 ->create();
If you already have a parent model instance that should be associated with the models you are creating, you may pass the model instance to the for
method:
1$user = User::factory()->create();23$posts = Post::factory()4 ->count(3)5 ->for($user)6 ->create();
1$user = User::factory()->create();23$posts = Post::factory()4 ->count(3)5 ->for($user)6 ->create();
Using Magic Methods
For convenience, you may use Laravel's magic factory relationship methods to define "belongs to" relationships. For example, the following example will use convention to determine that the three posts should belong to the user
relationship on the Post
model:
1$posts = Post::factory()2 ->count(3)3 ->forUser([4 'name' => 'Jessica Archer',5 ])6 ->create();
1$posts = Post::factory()2 ->count(3)3 ->forUser([4 'name' => 'Jessica Archer',5 ])6 ->create();
Many To Many Relationships
Like has many relationships, "many to many" relationships may be created using the has
method:
1use App\Models\Role;2use App\Models\User;34$user = User::factory()5 ->has(Role::factory()->count(3))6 ->create();
1use App\Models\Role;2use App\Models\User;34$user = User::factory()5 ->has(Role::factory()->count(3))6 ->create();
Pivot Table Attributes
If you need to define attributes that should be set on the pivot / intermediate table linking the models, you may use the hasAttached
method. This method accepts an array of pivot table attribute names and values as its second argument:
1use App\Models\Role;2use App\Models\User;34$user = User::factory()5 ->hasAttached(6 Role::factory()->count(3),7 ['active' => true]8 )9 ->create();
1use App\Models\Role;2use App\Models\User;34$user = User::factory()5 ->hasAttached(6 Role::factory()->count(3),7 ['active' => true]8 )9 ->create();
You may provide a closure based state transformation if your state change requires access to the related model:
1$user = User::factory()2 ->hasAttached(3 Role::factory()4 ->count(3)5 ->state(function (array $attributes, User $user) {6 return ['name' => $user->name.' Role'];7 }),8 ['active' => true]9 )10 ->create();
1$user = User::factory()2 ->hasAttached(3 Role::factory()4 ->count(3)5 ->state(function (array $attributes, User $user) {6 return ['name' => $user->name.' Role'];7 }),8 ['active' => true]9 )10 ->create();
If you already have model instances that you would like to be attached to the models you are creating, you may pass the model instances to the hasAttached
method. In this example, the same three roles will be attached to all three users:
1$roles = Role::factory()->count(3)->create();23$user = User::factory()4 ->count(3)5 ->hasAttached($roles, ['active' => true])6 ->create();
1$roles = Role::factory()->count(3)->create();23$user = User::factory()4 ->count(3)5 ->hasAttached($roles, ['active' => true])6 ->create();
Using Magic Methods
For convenience, you may use Laravel's magic factory relationship methods to define many to many relationships. For example, the following example will use convention to determine that the related models should be created via a roles
relationship method on the User
model:
1$user = User::factory()2 ->hasRoles(1, [3 'name' => 'Editor'4 ])5 ->create();
1$user = User::factory()2 ->hasRoles(1, [3 'name' => 'Editor'4 ])5 ->create();
Polymorphic Relationships
Polymorphic relationships may also be created using factories. Polymorphic "morph many" relationships are created in the same way as typical "has many" relationships. For example, if a App\Models\Post
model has a morphMany
relationship with a App\Models\Comment
model:
1use App\Models\Post;23$post = Post::factory()->hasComments(3)->create();
1use App\Models\Post;23$post = Post::factory()->hasComments(3)->create();
Morph To Relationships
Magic methods may not be used to create morphTo
relationships. Instead, the for
method must be used directly and the name of the relationship must be explicitly provided. For example, imagine that the Comment
model has a commentable
method that defines a morphTo
relationship. In this situation, we may create three comments that belong to a single post by using the for
method directly:
1$comments = Comment::factory()->count(3)->for(2 Post::factory(), 'commentable'3)->create();
1$comments = Comment::factory()->count(3)->for(2 Post::factory(), 'commentable'3)->create();
Polymorphic Many To Many Relationships
Polymorphic "many to many" (morphToMany
/ morphedByMany
) relationships may be created just like non-polymorphic "many to many" relationships:
1use App\Models\Tag;2use App\Models\Video;34$videos = Video::factory()5 ->hasAttached(6 Tag::factory()->count(3),7 ['public' => true]8 )9 ->create();
1use App\Models\Tag;2use App\Models\Video;34$videos = Video::factory()5 ->hasAttached(6 Tag::factory()->count(3),7 ['public' => true]8 )9 ->create();
Of course, the magic has
method may also be used to create polymorphic "many to many" relationships:
1$videos = Video::factory()2 ->hasTags(3, ['public' => true])3 ->create();
1$videos = Video::factory()2 ->hasTags(3, ['public' => true])3 ->create();
Defining Relationships Within Factories
To define a relationship within your model factory, you will typically assign a new factory instance to the foreign key of the relationship. This is normally done for the "inverse" relationships such as belongsTo
and morphTo
relationships. For example, if you would like to create a new user when creating a post, you may do the following:
1use App\Models\User;23/**4 * Define the model's default state.5 *6 * @return array7 */8public function definition()9{10 return [11 'user_id' => User::factory(),12 'title' => $this->faker->title(),13 'content' => $this->faker->paragraph(),14 ];15}
1use App\Models\User;23/**4 * Define the model's default state.5 *6 * @return array7 */8public function definition()9{10 return [11 'user_id' => User::factory(),12 'title' => $this->faker->title(),13 'content' => $this->faker->paragraph(),14 ];15}
If the relationship's columns depend on the factory that defines it you may assign a closure to an attribute. The closure will receive the factory's evaluated attribute array:
1/**2 * Define the model's default state.3 *4 * @return array5 */6public function definition()7{8 return [9 'user_id' => User::factory(),10 'user_type' => function (array $attributes) {11 return User::find($attributes['user_id'])->type;12 },13 'title' => $this->faker->title(),14 'content' => $this->faker->paragraph(),15 ];16}
1/**2 * Define the model's default state.3 *4 * @return array5 */6public function definition()7{8 return [9 'user_id' => User::factory(),10 'user_type' => function (array $attributes) {11 return User::find($attributes['user_id'])->type;12 },13 'title' => $this->faker->title(),14 'content' => $this->faker->paragraph(),15 ];16}
Running Seeders
If you would like to use database seeders to populate your database during a feature test, you may invoke the seed
method. By default, the seed
method will execute the DatabaseSeeder
, which should execute all of your other seeders. Alternatively, you pass a specific seeder class name to the seed
method:
1<?php23namespace Tests\Feature;45use Database\Seeders\OrderStatusSeeder;6use Database\Seeders\TransactionStatusSeeder;7use Illuminate\Foundation\Testing\RefreshDatabase;8use Illuminate\Foundation\Testing\WithoutMiddleware;9use Tests\TestCase;1011class ExampleTest extends TestCase12{13 use RefreshDatabase;1415 /**16 * Test creating a new order.17 *18 * @return void19 */20 public function test_orders_can_be_created()21 {22 // Run the DatabaseSeeder...23 $this->seed();2425 // Run a specific seeder...26 $this->seed(OrderStatusSeeder::class);2728 // ...2930 // Run an array of specific seeders...31 $this->seed([32 OrderStatusSeeder::class,33 TransactionStatusSeeder::class,34 // ...35 ]);36 }37}
1<?php23namespace Tests\Feature;45use Database\Seeders\OrderStatusSeeder;6use Database\Seeders\TransactionStatusSeeder;7use Illuminate\Foundation\Testing\RefreshDatabase;8use Illuminate\Foundation\Testing\WithoutMiddleware;9use Tests\TestCase;1011class ExampleTest extends TestCase12{13 use RefreshDatabase;1415 /**16 * Test creating a new order.17 *18 * @return void19 */20 public function test_orders_can_be_created()21 {22 // Run the DatabaseSeeder...23 $this->seed();2425 // Run a specific seeder...26 $this->seed(OrderStatusSeeder::class);2728 // ...2930 // Run an array of specific seeders...31 $this->seed([32 OrderStatusSeeder::class,33 TransactionStatusSeeder::class,34 // ...35 ]);36 }37}
Alternatively, you may instruct Laravel to automatically seed the database before each test that uses the RefreshDatabase
trait. You may accomplish this by defining a $seed
property on your base test class:
1<?php23namespace Tests;45use Illuminate\Foundation\Testing\TestCase as BaseTestCase;67abstract class TestCase extends BaseTestCase8{9 use CreatesApplication;1011 /**12 * Indicates whether the default seeder should run before each test.13 *14 * @var bool15 */16 protected $seed = true;17}
1<?php23namespace Tests;45use Illuminate\Foundation\Testing\TestCase as BaseTestCase;67abstract class TestCase extends BaseTestCase8{9 use CreatesApplication;1011 /**12 * Indicates whether the default seeder should run before each test.13 *14 * @var bool15 */16 protected $seed = true;17}
When the $seed
property is true
, the test will run the Database\Seeders\DatabaseSeeder
class before each test that uses the RefreshDatabase
trait. However, you may specify a specific seeder that should be executed by defining a $seeder
property on your test class:
1use Database\Seeders\OrderStatusSeeder;23/**4 * Run a specific seeder before each test.5 *6 * @var string7 */8protected $seeder = OrderStatusSeeder::class;
1use Database\Seeders\OrderStatusSeeder;23/**4 * Run a specific seeder before each test.5 *6 * @var string7 */8protected $seeder = OrderStatusSeeder::class;
Available Assertions
Laravel provides several database assertions for your PHPUnit feature tests. We'll discuss each of these assertions below.
assertDatabaseCount
Assert that a table in the database contains the given number of records:
1$this->assertDatabaseCount('users', 5);
1$this->assertDatabaseCount('users', 5);
assertDatabaseHas
Assert that a table in the database contains records matching the given key / value query constraints:
1$this->assertDatabaseHas('users', [3]);
1$this->assertDatabaseHas('users', [3]);
assertDatabaseMissing
Assert that a table in the database does not contain records matching the given key / value query constraints:
1$this->assertDatabaseMissing('users', [3]);
1$this->assertDatabaseMissing('users', [3]);
assertDeleted
The assertDeleted
asserts that a given Eloquent model has been deleted from the database:
1use App\Models\User;23$user = User::find(1);45$user->delete();67$this->assertDeleted($user);
1use App\Models\User;23$user = User::find(1);45$user->delete();67$this->assertDeleted($user);
The assertSoftDeleted
method may be used to assert a given Eloquent model has been "soft deleted":
1$this->assertSoftDeleted($user);
1$this->assertSoftDeleted($user);
assertModelExists
Assert that a given model exists in the database:
1use App\Models\User;23$user = User::factory()->create();45$this->assertModelExists($user);
1use App\Models\User;23$user = User::factory()->create();45$this->assertModelExists($user);
assertModelMissing
Assert that a given model does not exist in the database:
1use App\Models\User;23$user = User::factory()->create();45$user->delete();67$this->assertModelMissing($user);
1use App\Models\User;23$user = User::factory()->create();45$user->delete();67$this->assertModelMissing($user);