-
-
Save oluwajubelo1/09f87c29f8e6fab2af8d6d02667d683c to your computer and use it in GitHub Desktop.
Add the ability to replicate Laravel models to other models.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment