Skip to content

Instantly share code, notes, and snippets.

@nullthoughts
Created May 2, 2019 16:35
Show Gist options
  • Save nullthoughts/b0c72ae5744790e6286630efc86d82d4 to your computer and use it in GitHub Desktop.
Save nullthoughts/b0c72ae5744790e6286630efc86d82d4 to your computer and use it in GitHub Desktop.
Lock columns/attributes from updates in Laravel
<?php
namespace App\Traits;
trait LockColumns
{
/**
* Cast locked_columns as a JSON column
*
* @return void
*/
public function initializeLockColumns()
{
$this->casts['locked_columns'] = 'json';
}
/**
* Set a given attribute on the model if column is not locked
*
* @param string $key
* @param mixed $value
* @return mixed
*/
public function setAttribute($key, $value)
{
if ($this->isLocked($key)) {
return false;
}
return parent::setAttribute($key, $value);
}
/**
* Check if column is locked
*
* @param string $column
* @return boolean
*/
public function isLocked(string $column)
{
return in_array($column, (array) $this->locked_columns);
}
/**
* Lock a specific column
*
* @param string $column
* @return boolean
*/
public function lockColumn(string $column)
{
if ($this->isLocked($column)) {
return false;
}
return $this->update([
'locked_columns' => array_merge((array) $this->locked_columns, [$column])
]);
}
/**
* Unlock a specific column
*
* @param string $column
* @return boolean
*/
public function unlockColumn(string $column)
{
if (! $this->isLocked($column)) {
return false;
}
return $this->update([
'locked_columns' => array_diff($this->locked_columns, [$column]),
]);
}
/**
* Force update a value on a locked column
*
* @param string $column
* @param mixed $value
* @return boolean
*/
public function overrideLock(string $column, $value)
{
$this->unlockColumn($column);
$update = $this->update([$column => $value]);
$this->lockColumn($column);
return $update;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment