Search code examples
phpmysqldatabaselaravelreplicate

Replicate using foreign key - Laravel


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);

Solution

  • 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.