SilenceBringer's avatar

SilenceBringer wrote a reply+100 XP

4d ago

Eloquent inside a migration ?

Looks like I missed general question, my apologies. Please provide more details, what exactly "doesn't work" means. Any errors? At which step?

SilenceBringer's avatar

SilenceBringer wrote a reply+100 XP

1w ago

Eloquent inside a migration ?

The way we described above - by using DB facade in migration - is the only way I know. So, we have no choice =)

SilenceBringer's avatar

SilenceBringer wrote a reply+100 XP

1w ago

Eloquent inside a migration ?

As was mentioned before, migrations are about changing database SCHEMA, not the DATA. https://laravel.com/docs/13.x/migrations

Migrations are like version control for your database, allowing your team to define and share the application's database schema definition.

That's why I don't like the data changing in migration. But looks like Laravel do not suggest anything to archive the goals like in OP, that's why we do that in migration

SilenceBringer's avatar

SilenceBringer wrote a reply+100 XP

1w ago

Eloquent inside a migration ?

I had similar task years ago: need to add not null column to existing prod db and fill it with (computed) value from related tables. While I don't like this approach, passing years I still can't imagine better solution

  1. Add new nullable column
  2. Run the query (I used DB facade instead of Eloquent, but actually that's no difference) which fills the column with the data
  3. Make column "not null"

All of this inside one migration file.

I was not proud of this solution, but - as I told - I still do not not have better one.

SilenceBringer's avatar

SilenceBringer wrote a reply+100 XP

4mos ago

Correct usage of factories

If you need to create just 1 instance - mergeFillable method will help you, but you'll need to make the model first, and thet save it.

Vulnerability::factory()
	->make()
	->mergeFillable(['asset_id'])
	->save()

or you can move mergeFillable method to the factory callback https://laravel.com/docs/12.x/eloquent-factories#factory-callbacks

Not sure how good it will be with mass factory creation, just as the first idea