Skip to content

Instantly share code, notes, and snippets.

@mpociot
Created June 12, 2019 12:32
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save mpociot/ea51fed3b438e90b50228f4b113aba13 to your computer and use it in GitHub Desktop.
Save mpociot/ea51fed3b438e90b50228f4b113aba13 to your computer and use it in GitHub Desktop.
Add the ability to replicate Laravel models to other models.
<?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);
});
}
}
@Theodory
Copy link

Nice one

@zymawy
Copy link

zymawy commented Jun 12, 2019

Wow, 💯

@skyrpex
Copy link

skyrpex commented Jun 13, 2019

Yesterday I had the same problem. I came up with something similar, but ended using two different models (the new one extending the old one).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment