Skip to content

Instantly share code, notes, and snippets.

@emsifa
Last active September 12, 2015 23:38
Show Gist options
  • Save emsifa/7588f1da1e5fe8b823d4 to your computer and use it in GitHub Desktop.
Save emsifa/7588f1da1e5fe8b823d4 to your computer and use it in GitHub Desktop.
Trait Copyable, untuk copy record di database
<?php
namespace App\Http\Controllers;
use App\Thing;
class ContohController extends Controller
{
public function copySomething($id)
{
$thing = Thing::findOrFail($id);
$thing_copy = $thing->copy();
return ['copy_of_thing' => $thing_copy->toArray()];
}
}
<?php
namespace App\Traits;
trait Copyable
{
public function copy(array $updates = [], $save = true)
{
if(empty($this->getCopyable())) {
$class = get_class($this);
throw new \Exception("class {$class} is not copyable. Register some copyable attributes into \$copyable property to make it copyable.", 1);
}
$fillables = $this->getFillable();
$copyable = $this->getCopyable();
$copy = new static;
foreach($copyable as $attr) {
$copy->{$attr} = $this->{$attr};
}
foreach($updates as $attr => $value) {
if(in_array($attr, $fillables)) {
$copy->{$attr} = $value;
}
}
if(true === $save) $copy->save();
return $copy;
}
public function getCopyable()
{
return $this->copyable;
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits;
class Thing extends Model
{
use Traits\Copyable;
protected $copyable = ['name', 'description', 'etc'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment