Created
December 12, 2015 15:42
-
-
Save jlaswell/3219c4cd7426b60b97f4 to your computer and use it in GitHub Desktop.
Eloquent ReadOnly Trait
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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