Skip to content

Instantly share code, notes, and snippets.

@mkwsra
Created December 19, 2021 00:00
Show Gist options
  • Save mkwsra/a73b337616646e405d12c4dea8226777 to your computer and use it in GitHub Desktop.
Save mkwsra/a73b337616646e405d12c4dea8226777 to your computer and use it in GitHub Desktop.
Laravel - Has Statuses Trait
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
trait HasStatuses
{
const STATUS_DRAFT = 0;
const STATUS_ACTIVE = 1;
const STATUS_INACTIVE = 2;
use RetrieveConstants;
public static function getStatuses($prefix = 'STATUS_'): array
{
return array_flip(self::filterConstants($prefix));
}
// Perhaps you want a list of these statuses translated?
public static function getStatusesTranslated(): array
{
$statuses = self::getStatuses();
return collect($statuses)->map(function ($status) {
return trans('strings.'.Str::lower($status));
})->toArray();
}
// $model->is_active
public function getIsActiveAttribute(): bool
{
return $this->status === self::STATUS_ACTIVE;
}
// $model->is_inactive
public function getIsInactiveAttribute(): bool
{
return $this->status === self::STATUS_INACTIVE;
}
/**
* Scope a query to only include inactive records.
*
* @param Builder $query
*
* @return Builder
*/
public function scopeInactive($query)
{
return $query->where('status', self::STATUS_INACTIVE);
}
/**
* Scope a query to only include active records.
*
* @param Builder $query
*
* @return Builder
*/
public function scopeActive($query)
{
return $query->where('status', self::STATUS_ACTIVE);
}
/**
* Scope a query to only include everything BUT active records.
*
* @param Builder $query
*
* @return Builder
*/
public function scopeNotActive($query)
{
return $query->where('status', '!=', self::STATUS_ACTIVE);
}
/**
* Scope a query to only include draft records.
*
* @param Builder $query
*
* @return Builder
*/
public function scopeDraft($query)
{
return $query->where('status', self::STATUS_DRAFT);
}
/**
* Scope a query to only include everything BUT draft records.
*
* @param Builder $query
*
* @return Builder
*/
public function scopeNotDraft($query)
{
return $query->where('status', '!=', self::STATUS_DRAFT);
}
public function getStatusCssClassAttribute(): string
{
switch ($this->status) {
case self::STATUS_ACTIVE:
return 'success';
case self::STATUS_DRAFT:
return 'light';
case self::STATUS_INACTIVE:
return 'danger';
}
}
//...
// You might add a mutator to status column
// or you might want a status_name attribute as well :)
// Sky is the limit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment