Seed factory with booted function in model

Viewed 185

I would like to know how can I seed the data, when I use a booted function in model.

Currently I have this in the model :

class Event extends Model
{

    protected $fillable = ['title', ...];

    public static function booted()
    {
        static::creating(function ($event) {
            $event->user_id = auth()->id();
        });
    }
    ...
}

In the factory, I have this :

return [
    'title' => $this->faker->sentence(),
    'user_id' => User::all()->random()->id,
    ...
];

But when I execute the seeder, I have an error :

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into events (title, content, user_id, start_date, end_date, places_available, is_active, created_at, updated_at) values (Laudantium enim totam quibusdam mollitia aut et., Qui ducimus rerum quo necessitatibus in. Officia ea eveniet aut voluptas reiciendis quam eum quo. Sit eos velit tempore placeat., ?, 2019-07-07 14:15:24, 2021-07-14 13:57:23, 24, 1, 2019-07-07 14:15:24, 2021-07-22 15:04:30))

userId is ?

If I remove the function booted() in my model, it works.

2 Answers

In your model you can assign by default auth()->id() or, in case it's null, the value you have assigned in the create method:

public static function booted()
{
    static::creating(function ($event) {
        $event->user_id = auth()->id() ?? $event->user_id;
    });
}

You don't need the functionality on the creating event (since it won't be an auth user in seeding), so you can disable events on seeding, Muting Eloquent Events.

Event::withoutEvents(function () {
    Event::factory()...;
});
Related