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

pcmagas

Dimitrios Desyllas

Posted on January 15, 2024

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?

💖 💪 🙅 🚩
pcmagas
Dimitrios Desyllas

Posted on January 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related