Skip to content

Instantly share code, notes, and snippets.

@jbruni
Created January 31, 2017 12:38
Show Gist options
  • Save jbruni/3f6de84d8b6ca96cf574bb2b41671916 to your computer and use it in GitHub Desktop.
Save jbruni/3f6de84d8b6ca96cf574bb2b41671916 to your computer and use it in GitHub Desktop.
Laravel Read Only Model Trait
<?php
namespace app\Observers;
use Illuminate\Database\Eloquent\Model;
class ReadOnly
{
/**
* Listen to the Model creating event.
*
* @param Model $model
* @return void
*/
public function creating($model)
{
throw (new ReadOnlyException)->setModel(get_class($model));
}
/**
* Listen to the Model updating event.
*
* @param Model $model
* @return void
*/
public function updating($model)
{
throw (new ReadOnlyException)->setModel(get_class($model));
}
/**
* Listen to the Model saving event.
*
* @param Model $model
* @return void
*/
public function saving($model)
{
throw (new ReadOnlyException)->setModel(get_class($model));
}
/**
* Listen to the Model deleting event.
*
* @param Model $model
* @return void
*/
public function deleting($model)
{
throw (new ReadOnlyException)->setModel(get_class($model));
}
}
<?php
namespace app\Observers;
use RuntimeException;
class ReadOnlyException extends RuntimeException
{
/**
* Name of the affected Eloquent model.
*
* @var string
*/
protected $model;
/**
* Set the affected Eloquent model.
*
* @param string $model
* @return $this
*/
public function setModel($model)
{
$this->model = $model;
$this->message = "Not allowed to persist changes in read-only model [{$model}].";
return $this;
}
/**
* Get the affected Eloquent model.
*
* @return string
*/
public function getModel()
{
return $this->model;
}
}
<?php
namespace app\Traits;
use app\Observers\ReadOnly as ReadOnlyObserver;
trait ReadOnly
{
/**
* Boot the read only trait for a model.
*
* @return void
*/
public static function bootReadOnly()
{
static::observe(ReadOnlyObserver::class);
}
}
@jbruni
Copy link
Author

jbruni commented Jan 31, 2017

Note: Gist does not allow to use / character in file name to specify a subfolder. I substituted it by a - character. In our current project, all these are under a Models folder:

  • Traits/ReadOnly.php
  • Observers/ReadOnly.php
  • Observers/ReadOnlyException.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment