Sameh Ahmed
Sameh Ahmed

Reputation: 1

How to store associative array in Laravel

I'm new to Laravel, and I want to store this array in DB.

This is the php code of my array:

$socialNetwork = array();
$socialNetwork[0]["name"]= "Facebook";
$socialNetwork[0]["account"]= "facebook_account";
$socialNetwork[1]["name"]= "Twitter";
$socialNetwork[1]["account"]= "twitter_account";
$socialNetwork[2]["name"]= "Instagram";
$socialNetwork[2]["account"]= "insta_account";

The var_dump() looks like this:

array(3) {
  [0] => array(2) {
    ["name"] => string(8) "Facebook"
    ["account"] => string(16) "facebook_account"
  }
  [1] => array(2) {
    ["name"] => string(7) "Twitter"
    ["account"] => string(15) "twitter_account"
  }
  [2] => array(2) {
    ["name"] => string(9) "Instagram"
    ["account"] => string(13) "insta_account"
  }
}

I've tried several things but I can't get it to work!

Please help with the code. The table name is socialAccounts

Upvotes: 3

Views: 3001

Answers (1)

James
James

Reputation: 16339

Add a column in your database for this field; a JSON or TEXT type will do the job.

Next, you should add the column to the $casts array on your SocialAccount model:

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

Now, whenever you retrieve this value, it will be deserialized for you.

To store the value, just use json_encode():

$social_account->facebook_account = json_encode($facebookArrayData);
$social_account->save();

You can read more on attribute casting in the docs; https://laravel.com/docs/7.x/eloquent-mutators#attribute-casting

Upvotes: 4

Related Questions