skip to Main Content

I want the data obtained from find table1 to insert into table2

$table1= Table1::find($id);
$table2= new Table2();

without

$table2->field1 = $table1->field1;
$table2->field2 = $table1->field2;

where I have multiple fields
How do I use it? to be able to write short code

3

Answers


  1. mean like this?

    $table1 = Table1::find($id);
    
    Table2::create([
        'field1' => $table1->field1,
        'field2' => $table1->field2,
    ]);
    

    if the fields in table2 are same with table1

    $table1 = Table1::find($id);
    
    Table2::create($table1->toArray());
    
    Login or Signup to reply.
  2. Laravel has the replicate() function that will do your job.

    This is how you can use it:

    $table1 = Table1::find($id);
    $table2 = $table1->replicate();
    $table2 = $table2->toArray();
    Table2::create($table2);
    

    This function will clone your one model data into another object. If you want to change/add/replace any data from the model data then you can also add/modify it:

    $table1 = Table1::find($id);
    $table2 = $table1->replicate()->fill([
        'field_name' => 'value'        // Override any data
        'new_field_name' => 'value'    // Add new field data
    ]);
    $table2 = $table2->toArray();
    Table2::create($table2);
    

    I hope that this is what you are looking for. 😄😄

    Login or Signup to reply.
  3. If all the fields are same in both tables, you can try,

    $table1 = Table1::find($id);
    // Since $table1 is an object so you have to convert it into array bcs create accepts only array
    $table1 = $table1->toArray();
    // Also you will have id as autoincrement in table2 so you have to remove id of record of table1 before inserting to table2.
    unset($table1['id']);
    //Now insert array into table2
    Table2::create($table1);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search