Skip to content

Instantly share code, notes, and snippets.

@oluwajubelo1
Forked from mpociot/CanBeReplicated.php
Created August 27, 2019 19:51
Show Gist options
  • Select an option

  • Save oluwajubelo1/09f87c29f8e6fab2af8d6d02667d683c to your computer and use it in GitHub Desktop.

Select an option

Save oluwajubelo1/09f87c29f8e6fab2af8d6d02667d683c to your computer and use it in GitHub Desktop.

Revisions

  1. @mpociot mpociot created this gist Jun 12, 2019.
    29 changes: 29 additions & 0 deletions CanBeReplicated.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    <?php

    use Illuminate\Support\Arr;

    trait CanBeReplicated
    {
    public function replicateTo(string $model, array $with = null, array $except = null)
    {
    $defaults = [
    $this->getKeyName(),
    $this->getCreatedAtColumn(),
    $this->getUpdatedAtColumn(),
    ];

    $attributes = Arr::except(
    $this->attributes, $except ? array_unique(array_merge($except, $defaults)) : $defaults
    );

    $attributes = array_merge($attributes, $with ?? []);

    return tap(new $model, function ($instance) use ($attributes) {
    $instance->setRawAttributes($attributes);

    $instance->setRelations($this->relations);

    $instance->fireModelEvent('replicating', false);
    });
    }
    }