Summer Sale! All accounts are 50% off this week.

David1156's avatar

David1156 liked a comment+100 XP

9h ago

Eloquent inside a migration ?

Hello,

I have this code.

public function up(): void
{
    Schema::table('packages', function (Blueprint $table) {
        $table->foreignUlid('client_id')->after('site_id')->nullable()->constrained()->cascadeOnDelete();
    });

    $packages = Package::with('site')->get();

    foreach ($packages as $package) {
        $package->client_id = $package->site->client_id;

        $package->save();
    }
}

All works fine except saving the client_id for each package.

Why ?

If you have any idea, thanks to share ;).

V

David1156's avatar

David1156 wrote a reply+100 XP

9h ago

Eloquent inside a migration ?

Using Eloquent models inside migrations generally works, but it's considered risky for a few reasons: if the model's schema changes later (new casts, appended attributes, relationships that expect newer columns), old migrations using that model can break when run fresh on a new environment. A safer approach for data migrations is to query the table directly with the query builder instead of the model: phpDB::table('packages')->orderBy('id')->chunk(100, function ($packages) { foreach ($packages as $package) { DB::table('packages') ->where('id', $package->id) ->update(['client_id' => /* logic here */]); } }); This keeps the migration self-contained and immune to future changes in your model. If the transformation logic is complex, some teams create a dedicated console command for data backfills instead of putting it in a migration at all.

David1156's avatar

David1156 wrote a reply+100 XP

9h ago

Testing that the log record has been written.

If you're using the standard Laravel logging, you can use Log::spy() or Log::shouldReceive() in your test to assert that a specific message was logged, without actually writing to the log file. For example: phpuse Illuminate\Support\Facades\Log;

public function test_it_logs_the_expected_message() { Log::spy();

// trigger the code that logs
$this->postJson('/your-endpoint', [...]);

Log::shouldHaveReceived('info')
    ->with('Your expected log message');

} This is cleaner than actually reading the log file in tests, since it doesn't depend on file paths or log rotation. If you specifically need to test that something was written to a custom log channel, you can also fake just that channel using Log::channel('custom')->spy() in more recent Laravel versions.