In Laravel 10, the approach to using factories has changed compared to Laravel 7. The define method is no longer used. Instead, Laravel uses class-based factories. Here's how you can achieve what you're trying to do using the new factory system in Laravel 10.
First, ensure you have a factory for your UserAdmin model. You can generate a factory using Artisan:
php artisan make:factory UserAdminFactory --model=UserAdmin
Then, define the factory structure in database/factories/UserAdminFactory.php:
namespace Database\Factories;
use App\Models\UserAdmin;
use Illuminate\Database\Eloquent\Factories\Factory;
use Faker\Generator as Faker;
class UserAdminFactory extends Factory
{
protected $model = UserAdmin::class;
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->safeEmail,
];
}
}
Now, in your test, you can use this factory to create an array of attributes without persisting them to the database:
use App\Models\UserAdmin;
test('example test', function () {
$data = UserAdmin::factory()->make()->toArray();
$response = $this->postJson('/api/admin/users/store', $data);
$response->assertStatus(200);
});
In this example:
-
UserAdmin::factory()->make()creates a newUserAdmininstance without saving it to the database. -
->toArray()converts the model instance to an array of attributes, which you can then use to send as JSON payload in your test request.
This approach should work seamlessly with Laravel 10 and allows you to test your endpoints without persisting test data to your database.