eskimo
eskimo

Reputation: 2624

Add 5 minutes to timestamp after each model insert using Factory

When inserting models into the database I'd like to add 5 minutes to the timestamp property after each single model insert.

I thought that using Sequence like this would do the trick but it's not working: all models that are inserted still have the same timestamp.

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Factories\Sequence;

class TestSeeder extends Seeder
{
    public function run()
    {
        \App\Models\Test::factory(1000)
           ->state(new Sequence(
             fn () => ['timestamp' => now()->addMinutes(5)->toDateTimeString()],
           ))
           ->create();
    }
}

Upvotes: 1

Views: 755

Answers (3)

Arash Younesi
Arash Younesi

Reputation: 1760

You can use Eloquent Model Events: https://laravel.com/docs/8.x/eloquent#events

Ex:

class User extends Model
{
/**
 * The "booted" method of the model.
 *
 * @return void
 */
protected static function booted()
{
    static::created(function ($user) {
        // update the time or any fields else
    });
}
}

Upvotes: -2

Othmane Nemli
Othmane Nemli

Reputation: 1193

Use Factory Callbacks;

class TestFactory extends Factory
 {
   
    protected $model = Test::class;

    /**
     * Configure the model factory.
     *
     * @return $this
     */
    public function configure()
    {
        return $this->afterCreating(function (Test $test) {
           $test->update(['created_at' => Test::last()->created_at->addMinutes(5)]);
        });
    }
}

Seeder Class

public function run()
    {
        \App\Models\Test::factory(1000)->create();
    }

Upvotes: 1

Ali Ali
Ali Ali

Reputation: 1864

I will suggest this approach maybe with the need for some adjustments:

class TestSeeder extends Seeder
{
    private $testData = [];

    public function run()
    {
        $now = now();
        for ($i=0; $i < 100; $i++) {
            $testData[] = [
                'key1' => Str::random(10),
                'key2' => Str::random(10),
                'timestamp' => $now->addMinutes(5)->toDateTimeString()
            ];
        }
        foreach ($testData as $test) {
            \App\Models\Test::create($test);
        }
    }
}

Upvotes: 2

Related Questions