ActivityObserver.php 1.59 KB
<?php

namespace App\Observers;

use App\Models\Activity;

class ActivityObserver
{
    public bool $afterCommit = true;

    public function created(Activity $activity): void
    {
        $activity->tags()->sync(data_get($activity, 'expand.tag_ids', []));
        $activity->links()->wherePivot('type', 'lyricist')->syncWithPivotValues(data_get($activity, 'expand.lyricist.ids', []), ['type' => 'lyricist']);
        $activity->links()->wherePivot('type', 'composer')->syncWithPivotValues(data_get($activity, 'expand.composer.ids', []), ['type' => 'composer']);
        $activity->links()->wherePivot('type', 'arranger')->syncWithPivotValues(data_get($activity, 'expand.arranger.ids', []), ['type' => 'arranger']);
    }

    public function updated(Activity $activity): void
    {
        if ($activity->wasChanged('expand->tag_ids')) {
            $activity->tags()->sync(data_get($activity, 'expand.tag_ids', []));
        }
        if ($activity->wasChanged('expand->lyricist->ids')) {
            $activity->links()->wherePivot('type', 'lyricist')->syncWithPivotValues(data_get($activity, 'expand.lyricist.ids', []), ['type' => 'lyricist']);
        }
        if ($activity->wasChanged('expand->composer->ids')) {
            $activity->links()->wherePivot('type', 'composer')->syncWithPivotValues(data_get($activity, 'expand.composer.ids', []), ['type' => 'composer']);
        }
        if ($activity->wasChanged('expand->arranger->ids')) {
            $activity->links()->wherePivot('type', 'arranger')->syncWithPivotValues(data_get($activity, 'expand.arranger.ids', []), ['type' => 'arranger']);
        }
    }
}