Storing array or std object in database of Laravel app Storing array or std object in database of Laravel app laravel laravel

Storing array or std object in database of Laravel app


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'];


The best way since Laravel 5.1 is to CAST your table field like this:

class Mytable extends Model{    /**     * The attributes that should be casted to native types.     *     * @var array     */    protected $casts = [        'my_field' => 'array',    ];

Read more about attribute casting on official documents page of Laravel.The quote:

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast, while the value is the type you wish to cast to the column to. The supported cast types are: integer, real, float, double, string, boolean, object, array, collection, date and datetime.

The only limitation that docs does not say is that you cannot work with this array directly, like this

$myTable.my_field[]='new array element';

instead, you have to prepare array separately and then assign it to the field, like this:

$temp=[];$temp[]='new array element';$myTable.my_field[]=$temp;

If you use older version of Laravel, please use an answer providerd by The Alpha, or even better, quit your job :).