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)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay