21
13

More than 5 years have passed since last update.

Laravel で Model オブジェクトを新規データとしてコピーする

Posted at

replicate()っていうのを使う。

こんな感じ。

$user = User::find(1)
$new_user = $user->replicate();
$new_user->name = 'new name';
$new_user->save();

内部的には、こんな感じで実装されている。

    /**
     * Clone the model into a new, non-existing instance.
     *
     * @param  array  $except
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function replicate(array $except = null)
    {
        $except = $except ?: [
            $this->getKeyName(),
            $this->getCreatedAtColumn(),
            $this->getUpdatedAtColumn(),
        ];

        $attributes = array_except($this->attributes, $except);

        with($instance = new static)->setRawAttributes($attributes);

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

参考)
http://stackoverflow.com/questions/18322214/laravel4-duplicate-copy-table-row

21
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
13