K
K
keksum6662021-10-16 10:40:59
Laravel
keksum666, 2021-10-16 10:40:59

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);
    }
}


Forms model code:
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);
    }
}


Values ​​Pivot code:

class ValuesPivot extends MorphPivot
{
    protected $casts = [
        'values' => 'array'
    ];
}


Result with withPivot('values'):
616a81b06ca0a860684600.png

Result without withPivot('values'):
616a81ec87bbb156211332.png

This problem was solved by adding the following line to the ValuePivot class:
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 question

Ask a Question

731 491 924 answers to any question