Home > Software design >  Laravel ID increase on test how can fix
Laravel ID increase on test how can fix

Time:02-25

I have a problem that in my Laravel test always the ID goes further up, I want the entry always has the id 1,2,3. what is the best way to do this?

public function test_can_user_update_ticket()
{
    TicketPriority::factory(3)->create();
    TicketStatus::factory(3)->create();
    TicketType::factory(3)->create();
}

CodePudding user response:

The RefreshDatabase trait takes the most optimal approach to migrating your test database depending on if you are using an in-memory database or a traditional database. Use the trait on your test class and everything will be handled for you.

https://laravel.com/docs/8.x/database-testing#resetting-the-database-after-each-test

CodePudding user response:

You have to create records like this

factory(App\TicketPriority::class, 3)->create();
factory(App\TicketStatus::class, 3)->create();
factory(App\TicketType::class, 3)->create();

This will create 3 records for you with increment id. Also try to put id id type of each model as auto-increment.

$table->id();

CodePudding user response:

You have two options here:

(1) You can do an inline state transformation and change the property of that model when you instantiate it using the factory, e.g.:

$ticketPriority = TicketPriority::factory()->make([
    'id' => 3,
]);

(2) Otherwise you could set this in the factory class itself. The downside I think with this second option is that it won't be immediately obvious to anyone reading your tests that the model you are instantiating has a hardcoded id value and if you are using the factory in your application then it will always return the same value unless you override it using option (1), e.g.:

<?php
namespace Database\Factories;
use App\Models\TicketPriority;
use Illuminate\Database\Eloquent\Factories\Factory;
class TicketFactory extends Factory
{
/**
 * The name of the factory's corresponding model.
 *
 * @var string
 */
protected $model = TicketPriority::class;

/**
 * Define the model's default state.
 *
 * @return array
 */
public function definition()
{
    return [
        'id' => 3,
    ];
}
}

Either option will allow you to consistently return the same ID or any other attribute you want to stay the same for testing.

There's more on this in the Laravel docs https://laravel.com/docs/9.x/database-testing#defining-model-factories.

CodePudding user response:

You can pass to the create function an array with columnnames which you will modified. Like that:

for($i=0; $i<3; $i  ) {
    TicketPriority::factory()->create(['id' => ($i   1)]);
}
  • Related