0

I'm trying to use the model create option and this is my array:

$result = array(
            'match_id' => $input['id'],
            'score' =>  $input['score'],
            'result' =>  $input['result'],
            'headline' =>  NULL,
            'article' =>  $input['report'],
            'tries' =>  $input['try'],
            'try_amount' =>  $input['tryquant'],
            'conversions' =>  $input['conv'],
            'conv_amount' =>  $input['convquant'],
            'penalties' =>  $input['pens'],
            'pen_amount' =>  $input['penquant'],
            'dropgoals' =>  $input['dgs'],
            'dg_amount' =>  $input['dgquant']
            );

Result::create($result);

The contents of some of these are arrays themselves. eg:

$input['penquant'] = [
"4"
]

When I run my code, it saves the data to the DB simply as Array and throws up the following error:

ErrorException in helpers.php line 703: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

Can someone tell me what I'm doing wrong and how to fix it?

2
  • It's correct that you send key -> value pairs for saving. On other side, the values needs to be string. Use serialize/unserialize php functions. Check this link: stackoverflow.com/questions/10686333/… Commented Feb 18, 2016 at 17:06
  • Thank you @shamanSK, I've been a fool! Commented Feb 18, 2016 at 17:30

2 Answers 2

0

Shouldn't have rushed, forgot to use json_encode.

Sign up to request clarification or add additional context in comments.

Comments

0

The best is to use mutators and accessors in your model.

example of mutator

// convert pen_amount from snake case to studly case
// The set...attribute (the ... is you field name which is in studly case) helps transform the data before you save it 
// into the database
public function setPenAmountAttribute($value)
{
    $this->attributes['pen_amount'] = serialize($value);
}

example of an accessor is

// convert pen_amount from snake case to studly case
// the get...Attribute (the ... is you field name which is in studly case) helps you convert the data back to it original state
public function getPenAmountAttribute($value)
{
    return unserialize($value);
}

You can use accessors and mutators for all your fields that you want to save as array. This is elegant. No need to manually use json_encode and decode in your controllers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.