Newb 4 You BB
Newb 4 You BB

Reputation: 1355

Laravel Factory Sequence

I am trying to define a factory for a blog post. I would like to have a Sequence for the published field. I have tried a few different approaches but I have yet to be successful. Here is my current implementation. How could I do this correctly?

'published' => $this->sequence([now(), null])

I have also tried:

'published' => $this->sequence(now(), null)

I have additionally tried without the sequence() helper:

'published' => $this->state(new Sequence([now(), null]))

//and

'published' => new Sequence([now(), null])

API Docs: https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Factories/Sequence.html

Upvotes: 2

Views: 9022

Answers (3)

Kaleemullah
Kaleemullah

Reputation: 544

How you can get single record from table randomly in laravel.

 $password  = Hash::make('123456');
    return [
        'name' => $this->faker->name(),
        'email' => $this->faker->unique()->safeEmail(),
        'phone' => $this->faker->unique()->phoneNumber(),
        'email_verified_at' => now(),
        'password' => $password, // 123456
        'remember_token' => Str::random(10),
        'role_id'=>Role::inRandomOrder()->first()->id,
        'plan_id'=>Plan::inRandomOrder()->first()->id,
        'status'=>true,
        'activated_at'=>now(),
        'parent_id'=>null
    ];
}

Upvotes: 1

Newb 4 You BB
Newb 4 You BB

Reputation: 1355

I was attempting to do this incorrectly. Instead of creating the Sequence in the Factory, you should be creating the Sequence in the Seeder like so:

public function run()
{
    BlogPost::factory()
        ->count(6)
        ->sequence(
            ['published' => now()],
            ['published' => null]
        )
        ->create();
}

Upvotes: 2

shanpee
shanpee

Reputation: 21

Utilize configure() method of a Factory:

public function configure()
{
    return $this->sequence(
        [
            'published' => now()
        ], [
            'published' => null
        ]
    );
}

Docs mentions configure() in the context of a factory callbacks only but you may use any Factory::newInstance() caller here:

use App\Models\Post;

public function configure()
{
    return $this->afterMaking(function (Post $post) {
        //
    })->afterCreating(function (Post $post) {
        //
    })->sequence(
       //
    );
}

Upvotes: 2

Related Questions