Created
January 15, 2018 15:33
-
-
Save mohamednagy/085c9c768e931db9ad8fef1267371eea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use Illuminate\Database\Eloquent\Builder; | |
trait HasStatus | |
{ | |
public static function bootHasStatus() | |
{ | |
$status_column = (new static)->getStatusColumnName(); | |
foreach (static::$status as $statusValue => $statusStr) { | |
Builder::macro('set'.studly_case($statusStr), function() use ($statusValue, $status_column){ | |
return Builder::update([$status_column => $statusValue]); | |
}); | |
Builder::macro('only'.studly_case($statusStr), function() use ($statusValue, $status_column){ | |
return Builder::where($status_column, $statusValue); | |
}); | |
} | |
} | |
public function is($status) | |
{ | |
$statusValue = $this->getStatusValue($status); | |
return $this->{$this->getStatusColumnName()} == $statusValue; | |
} | |
public function scopeOnlyHasStatus($query, $status) | |
{ | |
$statusValue = $this->getStatusValue($status); | |
return $query->where($this->getStatusColumnName(), $statusValue); | |
} | |
public function setStatus($status) | |
{ | |
$statusValue = $this->getStatusValue($status); | |
return $this->update([$this->getStatusColumnName() => $statusValue]); | |
} | |
public function getStatusValue($status) | |
{ | |
$status = snake_case($status); | |
$statusValue = array_search($status, static::$status); | |
if ($statusValue !== false) { | |
return $statusValue; | |
} | |
throw new \Exception($status. 'doesnot exist'); | |
} | |
public function getStatusColumnName() | |
{ | |
return static::$status_column ?? 'status'; | |
} | |
public function __call($method, $args) | |
{ | |
if (starts_with($method, 'is')) { | |
$status = substr($method, 2); | |
return $this->is($status); | |
} | |
if (starts_with($method, 'set')) { | |
$status = substr($method, 3); | |
return $this->setStatus($status); | |
} | |
if (starts_with($method, 'only')) { | |
$status = substr($method, 4); | |
return parent::__call('onlyHasStatus', [$status]); | |
} | |
return parent::__call($method, $args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Laravel-Status
manage status likw moderation or anysomething else for elqouent models
Using!
add the status column to your migration
define the status into your elquent model
if you need to override the databse column or rename it
include the
HasStatus
into your modelexmaples
laravel-status works daynamicly according to your defined status, for example for status
pending
then you will be able use it asisPending
,setPending
,onlyPending