You can save/insert serialized data in to a TEXT
type field but for this you have to something using php
, for example:
$arr = array('x', 'y', 'z');
To insert this into a database field you can use serialize function like this
$serializedArr = serialize($arr);
Now, you can insert the $serializedArr
array in to databse and when you retrieve the data to use, just unserialize it using somethig like:
$record = SomeModel::find(1);
unserialize($record->field_name);
Also, you can use, Laravel's accessors-and-mutators to make the whole thing automated, check the manual, it's dead simple. If you need more help on this accessors-and mutators
then leave a message with your table
details.
Update:
Since Laravel 5.x
allows attribute casting so it's possible to cast attributes to another data type for converting on runtime. In this case, just declare a protected $casts
property for example:
protected $casts = [
'is_admin' => 'boolean', // Will convarted to (Bool)
'options' => 'array', // Will convarted to (Array)
];
The array
cast is particularly useful for working with columns that are stored as serialized JSON
. For example, if your database has a TEXT
type field that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP
array when you access it on your Eloquent
model and also it'll be automatically serialized back to JSON
when you set value to this property, for example:
$user = User::find(1);
// $options is an array...
$options = $user->options;
// options is automatically serialized back to JSON...
$user->options = ['foo' => 'bar'];