Hello there, I am writting a TRAIT to prevent model updates if it has certain condition, in this case if its relationship to TokenDocument > 1. Is not working.
Trait
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
trait FreezeIfAttachedToToken
{
public static function bootFreezeIfAttachedToToken()
{
static::saving(function (Model $model) {
if ($model->isAttachedToToken()) {
throw new \Exception("Cannot save: The record is attached to token");
}
});
static::updating(function (Model $model) {
if ($model->isAttachedToToken()) {
throw new \Exception("Cannot save: The record is attached to token");
}
});
static::creating(function (Model $model) {
if ($model->isAttachedToToken()) {
throw new \Exception("Cannot save: The record is attached to token");
}
});
static::deleting(function (Model $model) {
if ($model->isAttachedToToken()) {
throw new \Exception("Cannot delete: The record is attached to token");
}
});
}
public function isAttachedToToken()
{
return (bool) $this->TokenDocument->count();
}
}
Is not working at all, I also tried to "return false" instead of throwing an exception but ... nothing.
ANy help?I already spent 2 hours on this.
When I do something like:
$model = Model::find(id)
$model->data = "something";
$model->save()
I expect the exception, but instead model gets updated, and yes, It does meet the condition to be blocked