Friday, December 4, 2015

Problem with laravel save method

Problem with laravel save method:

Laravel save() method save data to database and return inserted data with inserted id . when we save another record after one using same object it  overwrite first record instead of creating new record .
Example

1. create AbcModel.php

public function Abc extend Model{

   public function createNew($data){
       $this->abc_id = $data->id;
        $this->name = $data->name;
     
   }
}
Note : Model Abc only save first record of $users array and in second times it update first record data with second record without creating second record in table.

Solution of above problem is create object of Abc Model inside createNew() method .

public function Abc extend Model{

   public function createNew($data){
    $abc = new Abc();
       $abc->abc_id = $data->id;
        $abc->name = $data->name;
     
   }
}


2. create AbcController.php
class NotificationController extends BaseController {

     public function createAbc (){
       
        $users = array(0 =>array('id' => '1','name'=>'Ravi')
                                  1 => array('id' => '2','name'=>'Ranjan'));

      $new = new Abc();
      foreach($users as $user){
           $new->createNew($user);
        }
     }

}

No comments:

Post a Comment