CodeWriteson Benim oluşturduğum eskiden kullandığım bir trait:
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
trait Toggleable
{
/**
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeActive($query): Builder
{
return $query->where('active', true);
}
/**
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePassive($query): Builder
{
return $query->where('active', false);
}
/**
* @param bool $status
* @param bool $silent Changes status without touching timestamps if it's true
* @return bool
*/
protected function changeStatus(bool $status, bool $silent = false): bool
{
$this->active = $status;
return $this->save([
'timestamps' => !$silent
]);
}
/**
* @param bool $silent
* @return bool
*/
public function switchOn(bool $silent = false): bool
{
return $this->changeStatus(true, $silent);
}
/**
* @param bool $silent
* @return bool
*/
public function switchOff(bool $silent = false): bool
{
return $this->changeStatus(false, $silent);
}
/**
* @param bool $silent
* @return bool
*/
public function toggle(bool $silent = false): bool
{
return $this->active
? $this->switchOff($silent)
: $this->switchOn($silent);
}
/**
* @return bool
*/
public function isActive(): bool
{
return (bool)$this->active;
}
/**
* @return bool
*/
public function isPassive(): bool
{
return !$this->isActive();
}
}