How to get fillable values on created event
Hi, I'm making a model Contact related with other models with a Morph relationship. In order to make recyclable code I made a Trait with the relationship and some actions to do by the model where I implement this trait.
As you can see, when the model implents that trait is creating I try to create the contacts related with it getting them from 'contactes' filled parameter. The problem appears when I assign that contacts (contactes in catalan language) to the related model: Illuminate\Database\QueryException is throwed because when the model is creating eloquent doesn't know their id (obviously).
My question is: How can I retrieve the filled parameters from created method in order to assign the contacts to it? On creating method I must delete contactes parameter because if not, eloquent search for that column on model table and it doesn't exists. How can I temporaly store that parameter to retrieve it after create? Or, another way, how can I prevent to write it into the database on creating event?
trait Contacteable
{
public function initializeContacteable()
{
if (! $this->with || empty($this->with)) {
$this->with = ['contactes'];
} else {
$this->with[] = 'contactes';
}
if (! $this->fillable || empty($this->fillable)) {
$this->fillable = ['contactes'];
} else {
$this->fillable[] = 'contactes';
}
}
public function contactes()
{
return $this->morphMany(Contacte::class, 'contacteable');
}
public static function bootContacteable()
{
static::creating(function ($model) {
if (array_key_exists('contactes', $model->toArray())) {
$model->createContactes();
}
unset($model['contactes']);
});
static::updating(function ($model) {
if (array_key_exists('contactes', $model->toArray())) {
$model->updateContactes();
}
});
static::deleted(function ($model) {
if (! uses_trait(SoftDeletes::class, $model)) {
foreach ($model->contactes as $contacte) {
$contacte->delete();
};
}
});
}
private function createContactes()
{
Validator::validate($this->toArray(), ['contactes' => [new Contactes]]);
foreach ($this['contactes'] as $contacte) {
$this->contactes()->create($contacte); // Error here
}
unset($this['contactes']);
}
private function updateContactes()
{
// TODO
}
}
Thanks
Please or to participate in this conversation.