Last active
September 12, 2015 23:38
-
-
Save emsifa/7588f1da1e5fe8b823d4 to your computer and use it in GitHub Desktop.
Trait Copyable, untuk copy record di database
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 | |
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()]; | |
} | |
} |
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 | |
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; | |
} | |
} |
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 | |
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