0

I want to replicate certain columns to another table.

foreach ($student->father_registrars as $getFatherData) {
            $fatherID = $getFatherData->id;
          
            // PROBLEM LAYS HERE   
            $fatherData =  \App\FatherRegistrars::where('id', $fatherID)->firstOrFail()();
            $fatherData->makeHidden(['birth', 'religion', 'education', 'citizenship', 'blood', 'id_card', 'residence_province', 'residence_regency', 'residence_district', 'residence_village', 'residence_address', 'residence_kode_pos', 'company_name', 'salary', 'company_address', 'company_province', 'company_regency', 'company_district', 'company_village', 'company_kode_pos']);
            
            $replicaFatherData = $fatherData->replicate();
            $fatherDatatoArray = $replicaFatherData->toArray();

            $father = \App\User::firstOrCreate($fatherDatatoArray);

            if ($isStudentExist >= 1) {
                $father->assignRole(['Parent', 'Guardian']);
            } else {
                $father->assignRole('Parent');
            }

            $father->password = $fatherData->password;

            $father->save();

            
        }

As you can see, I exclude fields birth, religion etc.. But still gives me an error Column not found: 1054 Unknown column 'birth' in 'where clause' (SQL: select * from users where...

Something weird when I try to run the same below code without foreach, but it works!

$find_one = \App\StudentRegistrars::where('id', $id)->firstOrFail();
        $find_one->makeHidden(['state', 'status', 'id', 'email_sent', 'address', 'provinces', 'regencies', 'districts', 'villages', 'kode_pos', 'nickname', 'nik', 'religion', 'citizenship', 'sequence', 'weight', 'height', 'blood', 'date', 'photo', 'family_card', 'birth_certificate', 'passed']);
        $new_user = $find_one->replicate();
        $new_user = $find_one->toArray();

        $user = \App\User::firstOrCreate($new_user);
        $user->assignRole('Student Registrars');
        $user->password = $find_one->password;
        $user->save();
Sead Lab
  • 181
  • 1
  • 14

1 Answers1

1

If you know which fields you want to keep between the two models:

$fatherOrigin = \App\FatherRegistrars::where('id', $fatherID)->first();
$fieldsToKeep = [ 'name', 'email', ... etc ... ];

$father = new \App\User(); 
foreach($fieldsToKeep as $field) {
   $father->$field = $fatherOrigin->$field;
}

If you know which field you want to discard:

$fatherOrigin = \App\FatherRegistrars::where('id', $fatherID)->first();
$fieldsToDiscard = [ 'birth', 'religion', ... etc ... ];
$originData = $fatherOrigin->toArray();

foreach($fieldsToDiscard as $field) {
   unset($originData[$field]);
}

$father = \App\User::firstOrCreate($originData); 
gbalduzzi
  • 8,482
  • 27
  • 54