Question

I am currently updating multiple rows in my database by doing the following:

I take an array in a post and loop through it, each member is an array of fieldname=>value and I am doing an update on each one. the problem is that the mutators I have set up do not get run when I update this way. is there another way to update that is efficient and will call the mutators?

code:

foreach ($post['row'] as $row) {
     Instances::where('id', $row['id'])->update($row);
  }
Was it helpful?

Solution

You probably will be able to use your mutators by doing something like:

foreach ($post['row'] as $row) 
{
     $data = Instances::where('id', $row['id'])->first();

     foreach($row as $key => $value)
     {
        $data->$key = $value; // which is the same as $data->setAttribute($key, $value);
     }

     $data->save();
}

Can't you just override the update method?

class BaseModel extends Eloquent {

    public function update($array)
    {
        parent::update($this->trimAll($array));
    }

    public function trimAll($data)
    {
        /// trim them here
    }

}

And you can keep using:

Instances::where('id', $row['id'])->update($row);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top