Installation:
composer require repat/laravel-job-models
Ensure queue:table and queue:failed-table have been run (php artisan queue:table and php artisan queue:failed-table).
First Use Case: Access jobs directly via Eloquent:
use Repat\LaravelJobs\Job;
use Repat\LaravelJobs\FailedJob;
// Fetch a job
$job = Job::find(1);
// Fetch a failed job
$failedJob = FailedJob::first();
Key Features to Explore:
$job->payload (cast to array) or $job->command (unserialized).$job->reserved_at, $job->available_at, etc., are automatically cast to Carbon.$job->display_name, $job->max_tries, etc., for direct access to payload keys.Querying Jobs:
// Find jobs by payload data
$jobs = Job::where('payload->data.commandName', 'SendEmail')
->where('payload->data.user_id', 1)
->get();
// Find jobs reserved in the last hour
$recentJobs = Job::where('reserved_at', '>', now()->subHour())
->orderBy('reserved_at', 'desc')
->get();
Handling Failed Jobs:
// Get failed jobs with a specific exception
$failedJobs = FailedJob::where('exception', 'like', '%TimeoutException%')
->get();
// Retry a failed job (manually)
$failedJob = FailedJob::find(1);
dispatch(new $failedJob->payload['data']['commandName']($failedJob->payload['data']));
$failedJob->delete(); // Clean up after retry
Job Metadata Inspection:
// Inspect job attributes
$job = Job::find(1);
$job->display_name; // Access payload['data']['commandName']
$job->max_tries; // Access payload['maxTries']
$job->delay; // Access payload['delay']
Integration with Job Processing:
// Before processing a job, check its status
$job = Job::find($jobId);
if ($job->available_at > now()) {
return response()->json(['status' => 'job_unavailable']);
}
// After processing, update job status (if needed)
$job->update(['available_at' => null]);
Customizing Job Models: Extend the base models for additional logic:
namespace App\Models;
use Repat\LaravelJobs\Job as BaseJob;
class Job extends BaseJob
{
public function user()
{
return $this->belongsTo(User::class, 'payload->data.user_id');
}
public function scopeForUser($query, $userId)
{
return $query->where('payload->data.user_id', $userId);
}
}
Payload Serialization:
payload column is serialized by default. If you modify the payload structure (e.g., add/remove keys), ensure backward compatibility or handle deserialization errors:
try {
$job->command; // Triggers deserialization
} catch (\Exception $e) {
log::error("Failed to deserialize job payload: " . $e->getMessage());
}
Carbon Casting:
available_at) will not be cast to Carbon. Handle null checks explicitly:
if ($job->available_at && $job->available_at > now()) {
// Job is not available yet
}
Queue Table Configuration:
config/queue.php, ensure the models are updated to match:
// In app/Providers/AppServiceProvider@boot()
\Repat\LaravelJobs\Job::setTable(config('queue.table'));
\Repat\LaravelJobs\FailedJob::setTable(config('queue.failed_table'));
Payload Mutators:
payload attribute may not trigger mutators. Use the getters/setters or update the underlying data array:
// Correct way to update payload data
$job->payload['data']['new_key'] = 'value';
$job->save();
Performance:
with() selectively:
$jobs = Job::where('id', $ids)->with(['user' => function($query) {
$query->select('id', 'name'); // Only load necessary fields
}])->get();
Inspect Raw Payload:
Use dd($job->getRawOriginal('payload')) to debug serialization issues.
Query Logging: Enable Laravel query logging to inspect complex payload queries:
\DB::enableQueryLog();
$jobs = Job::where('payload->data.user_id', 1)->get();
dd(\DB::getQueryLog());
Failed Job Exceptions:
The exception column in failed_jobs stores serialized exceptions. Use unserialize() or json_decode() to inspect:
$exception = unserialize($failedJob->exception);
// or
$exception = json_decode($failedJob->exception, true);
Custom Attributes: Add computed attributes to the models for common job metadata:
// In Job model
public function getIsDelayedAttribute()
{
return $this->available_at && $this->available_at > now();
}
Observers: Track job lifecycle events (e.g., job reserved, failed):
// In app/Providers/AppServiceProvider@boot()
\Repat\LaravelJobs\Job::observe(JobObserver::class);
API Resources: Create API resources to format job data for responses:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class JobResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'command' => $this->command_name,
'status' => $this->available_at ? 'pending' : 'reserved',
'payload' => $this->payload['data'],
];
}
}
Queue Events:
Listen to queue events (e.g., job.processing, job.failed) to sync with the models:
// In EventServiceProvider
protected $listen = [
'Illuminate\Queue\Events\JobProcessed' => [
\App\Listeners\UpdateJobStatus::class,
],
];
How can I help you explore Laravel packages today?