0

I am trying to replicate certain data in my DB and I followed the steps as in the following link. Laravel 4: replicate to table However, I need to replicate some other data using only a foreign key.I tried to use the find() method to get my data but returned nothing.The where clause returns my data but in the form of array which isn't accepted by the replicate method.

Anhy idea what i am doing wrong and how can I replicate my other data?!

Code:

$item = Cv::find($cv_id);
        // return $item;
        $clone = $item->replicate();
        unset($clone['created_at'],$clone['updated_at']);
        $data = json_decode($clone, true);
        Cv::create($data);

        //Skills
        // return $cv_id;
        $skills = Skill::where('cv_id', $cv_id);
        $cloneSkills = $skills->replicate();
        unset($cloneSkills['created_at'],$cloneSkills['updated_at']);
        $skillData = json_decode($cloneSkills,true);
        Skill::create($skillData);
Community
  • 1
  • 1
omarsafwany
  • 3,695
  • 8
  • 44
  • 75

1 Answers1

1

For replicating skills you should probably use:

$skills = Skill::where('cv_id', $cv_id)->get();

foreach ($skills as $skill) {

    $cloneSkill = $skill->replicate();
    unset($cloneSkill['created_at'], $cloneSkill['updated_at']);
    $skillData = json_decode($cloneSkill, true);
    Skill::create($skillData);
}

You need to use get() to get all data and because $skills is Collection you need to use loop to replicate each skill.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • OK it worked but the cv_id in Skill table wasn't changed to the new one.It stayed as the previous one. Why did that happen? – omarsafwany Oct 02 '14 at 12:27
  • @omarsafwany Because you use the same variable to find skills `$cv_id`. If you want to use other id, you need to find in CV again another item and change `$cv_id` to its id. – Marcin Nabiałek Oct 02 '14 at 12:29