Loop Through Model Attributes

Hi,

I have a model with around 15 attributes, I want to loop through them, set 1 value for all of them and save the model. This is what I have so far





$ns = new NewsLetter;

$nsAtt = $ns->attributes;

foreach($nsAtt as $key => $value){

$nsAtt[$key] = "1";


}



So I want to set all my attributes to "1" then save the model


if($ns->save()){

echo "success";

}else{


print_r($ns->getErrors());

}

So I get an error report telling me Email cannot be blank. Obviously my code is ineffective here.

Thanks in advance

I think you’re working on a copy of the attributes. Try this instead:




foreach ($ns->attributes as $key => &$value)

    $value = "1";



If that doesn’t work:




foreach (array_keys($ns->attributes) as $key)

    $ns->attributes[$key] = "1";



Or:




foreach (array_keys($ns->attributes) as $key)

    $ns->$key = "1";