Expert assistant for badrshs/laravel-data-jobs package - Laravel one-time data migration framework with priority queuing and auto-discovery
Expert coding assistant for the `badrshs/laravel-data-jobs` Laravel package - a framework for managing one-time data migration jobs with priority support, execution tracking, and automatic discovery.
This is a Laravel package that provides infrastructure for one-time data migration jobs implemented as Artisan commands. Jobs use the `DataJobable` trait for automatic discovery, priority sorting, and execution state tracking.
**Key Architecture Points:**
When creating or modifying data job commands:
```php
use Badrshs\LaravelDataJobs\Contracts\DataJobable;
use Illuminate\Console\Command;
class MigrateUsersCommand extends Command {
use DataJobable;
protected $signature = 'migrate:users';
// Lower priority = runs first (default: 100)
public function getJobPriority(): int {
return 10;
}
// Optional metadata for logging
public function getJobParameters(): array {
return ['batch' => 'users-2024'];
}
public function handle() {
// Migration logic here
return Command::SUCCESS;
}
}
```
Located in `src/Console/RunDataJobsCommand.php#L130-L150`. Auto-discovers jobs by:
1. Scanning all registered Artisan commands via `$this->getApplication()->all()`
2. Checking for `DataJobable` trait using `class_uses_recursive()`
3. Sorting by priority via `usort()` at runtime
4. No configuration or registration files needed
Jobs tracked in `data_jobs_log` table with columns:
Execution flow in `RunDataJobsCommand.php#L197-L244`:
1. Check status before run (skip if completed unless `--force`)
2. Update to `running` before execution
3. Catch `\Throwable`, log errors, update to `failed` or `completed`
```powershell
vendor/bin/phpunit
php artisan data-jobs:install [--force]
php artisan data:run-jobs
php artisan data:run-jobs --job=MigrateUsersCommand --force
php artisan data:run-jobs --fresh
```
Located in `tests/TestCase.php`. Uses Orchestra Testbench with:
Use snake_case with `@test` annotation:
```php
/** @test */
public function it_discovers_commands_with_data_jobable_trait(): void
{
// Test logic
}
/** @test */
public function it_executes_jobs_in_priority_order(): void
{
// Test logic
}
```
Follow emoji-prefixed patterns from `RunDataJobsCommand.php#L79-L104`:
Example:
```php
$this->info('🚀 Starting data job execution...');
$this->line("▶️ Running: {$command->getName()}");
$this->info('✅ Job completed successfully');
```
Commands must return exit codes, not throw exceptions:
```php
try {
// Job logic
return Command::SUCCESS;
} catch (\Throwable $e) {
$this->error("❌ Error: {$e->getMessage()}");
return Command::FAILURE;
}
```
Framework catches exceptions in `RunDataJobsCommand.php#L207-L244` and stores in `error_message` column.
Use DB facade directly (not Eloquent models):
```php
use Illuminate\Support\Facades\DB;
// Idempotent logging pattern
DB::table('data_jobs_log')->updateOrInsert(
['job_class' => get_class($command)],
[
'status' => 'running',
'priority' => $command->getJobPriority(),
'parameters' => json_encode($command->getJobParameters()),
'executed_at' => now(),
]
);
```
Published to `config/data-jobs.php`:
```php
return [
// Custom log table name
'log_table' => env('DATA_JOBS_LOG_TABLE', 'data_jobs_log'),
// Auto-run jobs on deployment (use with caution)
'auto_run' => env('DATA_JOBS_AUTO_RUN', false),
// Enable/disable execution logging
'logging_enabled' => env('DATA_JOBS_LOGGING_ENABLED', true),
];
```
Use `release.ps1` PowerShell script (not `.bat`):
```powershell
.\release.ps1
.\release.ps1 -Version "1.2.0"
```
Script performs:
1. Auto-increment patch from last `v*` git tag
2. Stage changes and commit with version message
3. Create and push git tag (format: `v1.2.3`)
4. Push to `origin main` branch
5. Packagist syncs automatically
1. **Job execution uses `run()` method**: Pass `ArrayInput([])` and current OutputInterface, not `call()` or direct `handle()`
2. **Priority sorting is runtime-only**: Use `usort()` in command discovery, not database ORDER BY
3. **Unique constraint on job_class**: Enables `updateOrInsert()` pattern for idempotent logging
4. **Migration timestamp is fixed**: `2024_01_01_000000_create_data_jobs_log_table.php` ensures consistent load order
5. **No async execution**: Jobs run sequentially in single process - not queued or parallelized
6. **Auto-discovery scans all commands**: Performance consideration for apps with many commands
1. **Priority assignment**: Reserve 1-10 for critical schema changes, 50-100 for data migrations, 100+ for cleanup tasks
2. **Error messages**: Include context in exceptions - job class name, affected records count, specific IDs
3. **Idempotency**: Design jobs to be safely re-runnable with `--force` flag
4. **Progress indicators**: Use `$this->output->progressStart()` for long-running jobs
5. **Testing**: Mock file system and external APIs, use database transactions for cleanup
6. **Documentation**: Add `@param` and `@return` PHPDoc to all public methods
**Add new data job:**
1. Create command class in `app/Console/Commands`
2. Add `use DataJobable` trait
3. Implement `getJobPriority()` if non-default priority needed
4. No registration required - auto-discovered
**Debug job discovery:**
```php
// In RunDataJobsCommand, add before sorting:
dump(array_map(fn($c) => get_class($c), $dataJobs));
```
**Reset job status:**
```sql
-- Reset specific job
UPDATE data_jobs_log SET status = 'pending' WHERE job_class = 'App\\Console\\Commands\\MigrateUsersCommand';
-- Reset all failed jobs
UPDATE data_jobs_log SET status = 'pending' WHERE status = 'failed';
```
**Add custom logging:**
```php
DB::table(config('data-jobs.log_table'))->updateOrInsert(
['job_class' => get_class($this)],
['parameters' => json_encode(['custom_field' => 'value'])]
);
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/laravel-data-jobs-development-assistant/raw