Answer the question
In order to leave comments, you need to log in
How to cast for a polymorphic pivot table?
Hello! It has 2 entities Form and Event are interconnected by a many-to-many polymorphic relationship, in the pivot table there is a pivot called values, it is stored as a json field. Is there any way to use cast for this field?
Event model code:
class Event extends Model
{
use HasFactory;
use HasJsonRelationships;
protected $fillable = [
'title'
];
protected $casts = [
'pivot.values' => 'array',
];
public function forms()
{
return $this->morphToMany(Form::class, 'entity', 'entities_forms')
->withPivot('values')
->using(ValuesPivot::class);
}
}
class Form extends Model
{
use HasFactory;
protected $fillable = [
'title',
'structure',
];
protected $casts = [
'entity_id' => 'array',
'structure' => 'array',
'pivot.values' => 'array',
];
public function events()
{
return $this->morphedByMany(Event::class, 'entity', 'entities_forms')->withPivot('values')->using(ValuesPivot::class);
}
}
class ValuesPivot extends MorphPivot
{
protected $casts = [
'values' => 'array'
];
}
protected $fillable = [
'value'
];
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question