Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Job Models Laravel Package

repat/laravel-job-models

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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).

  2. 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();
    
  3. Key Features to Explore:

    • Payload Access: $job->payload (cast to array) or $job->command (unserialized).
    • Carbon Casting: $job->reserved_at, $job->available_at, etc., are automatically cast to Carbon.
    • Payload Getters: $job->display_name, $job->max_tries, etc., for direct access to payload keys.

Implementation Patterns

Common Workflows

  1. 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();
    
  2. 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
    
  3. 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']
    
  4. 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]);
    
  5. 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);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Payload Serialization:

    • The 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());
      }
      
  2. Carbon Casting:

    • Null values in timestamp fields (e.g., 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
      }
      
  3. Queue Table Configuration:

    • If you’ve customized the queue table names in 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'));
      
  4. Payload Mutators:

    • Directly modifying the 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();
      
  5. Performance:

    • Avoid eager-loading large payloads unnecessarily. Use with() selectively:
      $jobs = Job::where('id', $ids)->with(['user' => function($query) {
          $query->select('id', 'name'); // Only load necessary fields
      }])->get();
      

Debugging Tips

  1. Inspect Raw Payload: Use dd($job->getRawOriginal('payload')) to debug serialization issues.

  2. 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());
    
  3. 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);
    

Extension Points

  1. 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();
    }
    
  2. Observers: Track job lifecycle events (e.g., job reserved, failed):

    // In app/Providers/AppServiceProvider@boot()
    \Repat\LaravelJobs\Job::observe(JobObserver::class);
    
  3. 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'],
            ];
        }
    }
    
  4. 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,
        ],
    ];
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle