nirvair
nirvair

Reputation: 4180

saving JSON string in laravel

I am trying to save a JSON string to the database.

this is the error that I get:

exception 'ErrorException' with message 'preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

And this is how my JSON looks like:

"metadata": {
      "is_ivr": 0,
      "is_upgradable": 1,
      "is_sms": 0,
      "is_design": 0,
      "threshold_amount": 0,
      "post_threshold": 0,
      "pre_threshold": 0
    }

I want to save the value of metadata as string.

I tried doing this:

$data = $request->input('data');
$data['metadata'] = json_encode($data['metadata']);

Result of dd($data);

array:8 [
  "product_name" => "Pulse"
  "parent_product" => 0
  "product_description" => "goes here"
  "metadata" => array:7 [
    "is_ivr" => 0
    "is_upgradable" => 1
    "is_sms" => 0
    "is_design" => 0
    "threshold_amount" => 0
    "post_threshold" => 0
    "pre_threshold" => 0
  ]
  "price_period" => 1
  "price_variation" => 2
  "outlet_pricing" => 0
  "status" => 1
  ]
]

Upvotes: 0

Views: 10034

Answers (3)

Crisoforo Gaspar
Crisoforo Gaspar

Reputation: 3830

You need to serialize your data before save the JSON into the DB for example:

$data = serialize( json_encode( $data['metadata'] ) );
// Insert $data into the DB

Now if you want to reuse the data in PHP from the DB you need to run the opposite unserialize.

$raw_data = // query to get the data from the DB
$data = unserialize( $raw_data );

This will allow you to save data structures such as arrays. From the PHP documentation

Generates a storable representation of a value.

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

To be honest I don't know what's going on at the moment, but open your model (I don't know its name because you haven't showed it) and fill:

protected $casts = [
    'metadata' => 'array',
];

assuming you haven't done it yet.

Now, when you insert data into database don't use any json_encode, simply you can use:

$data = $request->input('data');

without:

$data['metadata'] = json_encode($data['metadata']);

Using casts property Laravel will automatically convert array data to json when inserting into database and automatically run json_decode to get array when getting data from database.

Upvotes: 7

Sari Yono
Sari Yono

Reputation: 577

use Implode(); and separate it by commas or if you would like you can access the property of the array by calling its index directly $data['metadata'][index]

whats happening is you are calling a regex on an array not a value.

Upvotes: 0

Related Questions