DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

Why I cannot populate using afterMaking with a referencing record in my factories?

As I ask Upon:

I haver the following factory:

namespace Database\Factories
use App\Models\Policy;
use App\Models\A;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\A>
 */
class VersionFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        $this->afterMaking(function (Version $model){
           if(!empty($model->policy_id)){
               return;
           }

           $randomB = B::inRandomOrder()->first();

I try to populate a table's foreighn key. But it seems that factorie's afterMaking closure is not called thuw the foreighn key is not populated.

Can you help me with that?

Top comments (0)