Search code examples
laraveloctobercms

Replicate record in OctoberCMS


I am attempting to create a function that will duplicate an existing record using the laravel 'replicate' method.

Here is what I what but it's not working as expected.

updateContact.php

use Cms\Classes\ComponentBase;
use Input;
use Validator;
use Redirect;
use Itinify\Itinify\Models\Contact;
use Itinify\Itinify\Models\Organisation;
use Carbon\Carbon;

public function replicateRecord()
    {
        $contact = Contact::find($this->param('id'));

        $newContact = $contact->replicate();

        $newContact->created_at = Carbon::now();

        $newContact->save();

        return Redirect::to('/contacts/'.$newContact->id);

    }
default.htm

<div class="col-md-12">
            <form data-request="replicateRecord">
                <button aria-label="" class="btn btn-danger pull-right btn-lg btn-block" type="submit">Duplicate
                </button>
</form>
</div>

Solution

  • You need to pass one param to the function ($contact_id or $request) in order to controller can understand which contact to replicate.

    Make sure that contact table in your database does not have a UNIQUE column. If has, to exclude one or more attributes from being replicated, you may pass an array to the replicate method:

    $contact->replicate(['field']);
    

    Remove this line (of course, it does not affect your problem):

    $newContact->created_at = Carbon::now(); // not necessary