Inserting multiple records in a plugin I'm building a plugin and have a form in the plugin's CP page that allows admins to save access codes. The form is a simple textarea where each line is a separate access code. 

I'm wondering what the best practice is in terms of inserting these records into the database?

Controller:

// This returns an array of codes to be inserted
$codes = explode("\r\n", craft()-&gt;request-&gt;getPost('codes'));

foreach($codes as $code) {
    $codeModel = new Portal_CodeModel();
    $codeModel-&gt;code = $code;
    $codeModels[] = $codeModel;
}

$success = craft()-&gt;portal_code-&gt;addCodes($codeModels);


Service:

public function addCodes($codes) {

    foreach($codes as $code) {

      Portal_CodeRecord::model()-&gt;insert(array(
          'code'        =&gt; $code,
          'code_used'   =&gt; 0
      ));

    }

}


Record:

class Portal_CodeRecord extends BaseRecord {

    public function getTableName() {
        return 'portal_codes';
    }

    protected function defineAttributes() {
        return array(
            'code'          =&gt; AttributeType::String,
            'code_used'     =&gt; AttributeType::Bool
        );
    }
}
Go with #1.  It looks like you've already got a Portal_CodeModel created, you just need to populate them from the controller, perform validation (if any), then pass the array of Portal_CodeModel objects to your service.

You'll want to remove the Portal_CodeModel type hint from your service's addCodes signature (or change it to array) since you're passing in an array of objects, instead of a single one.

Here's an example in your controller with any code validation:

$codeModels = array();
$codes = explode("\r\n", craft()-&gt;request-&gt;getPost('codes'));

$success = craft()-&gt;portal_code-&gt;addCodes($codes);


And in your service:

public function addCodes($codes)
{

    foreach($codes as $code)
    {
        $existingCode = Portal_CodeRecord::model()-&gt;findByAttributes(array(
            'code' =&gt; $code,
        ));

        if ($existingCode)
        {
            $existingCode-&gt;code_used = 1;
            $existingCode-&gt;save();

            {# or whatever else you want to do when the code already exists in the database #}
        }
        else
        {
            $codeRecord = new Portal_CodeRecord();
            $codeRecord-&gt;code = $code;
            $codeRecord-&gt;code_used = 0;
            $codeRecord-&gt;save();
        }
    }


}