Skip to content

Instantly share code, notes, and snippets.

@jlaswell
Created December 12, 2015 15:42

Revisions

  1. jlaswell created this gist Dec 12, 2015.
    27 changes: 27 additions & 0 deletions ReadOnly
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    <?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.');
    });
    }
    }
    }