Using Common StatusTrait in Laravel in multiple models

Laravel
August 26, 20201 minuteuserMitul Golakiya
Using Common StatusTrait in Laravel in multiple models

Recently, we were working on a laravel app where we have a status column in multiple models. We have multiple processes going on for which we have different jobs.

Initially job status will be "Pending", then each job will take one record, change the status to "Running" and process that record, and update the status to either "Completed" or "Failed".

We have constants for each status. Something like below,

static $STATUS_PENDING = 0; 
static $STATUS_RUNNING = 1; 
static $STATUS_COMPLETED = 2; 
static $STATUS_FAILED = 3;

And the problem is, we need to go and define the status in every model that we have (around 10+ models).

Then we have functions to update status and check the status in each model like,

public function markRunning($saveRecord = true) 
{     
    $this->status = static::$STATUS_RUNNING;
    if ($saveRecord) {
        $this->save();
    }
}

public function isRunning()
{
    return $this->status === static::$STATUS_RUNNING;
}

And above functions existed for each 4 status. So what we did is, we created a common StatusTrait which can be used across multiple models.

Here is the code of StatusTrait that you can find for that.

Then in each model, we use this trait. For e.g.,

class SavePdf extends Model 
{     
    use StatusTrait;
    .....
}

And then can use any method of trait in all the models,

... 
$savePdf = new SavePdf(); 
$savePdf->markRunning(); 
...

Or we can check if the status of the model is running or not. For e.g.,

... 
if ($savePdf->isRunning()) 
{     
    // logic here 
} 
...

This is how we have saved tons of writing code and optimized the code. Another advantage is, we can just update the value of any status from one single place.

You can also check this kind of pattern and do something like this.