Skip to content

Instantly share code, notes, and snippets.

@jlaswell
Created December 12, 2015 15:42
Show Gist options
  • Save jlaswell/3219c4cd7426b60b97f4 to your computer and use it in GitHub Desktop.
Save jlaswell/3219c4cd7426b60b97f4 to your computer and use it in GitHub Desktop.
Eloquent ReadOnly Trait
<?php
namespace App\Models\Traits;
use ReflectionClass;
/**
* Simply add this trait to make your model read only.
* This needs to be added to the model itself and not to the base Eloquent Model.
*/
trait ReadOnly
{
public static function boot()
{
parent::boot();
$instance = new ReflectionClass(static::class);
$observables = array_diff(
$instance->newInstance()->getObservableEvents(),
['restoring', 'restored']
);
foreach ($observables as $event) {
static::$event(function ($model) {
throw new \Exception('The ' . static::class . ' class is restricted to be read only.');
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment