php - Store array of objects in DB column. Laravel -
trying store array of objects in db , getting error : array_merge(): argument #1 not array
$tmp = new projects; $tmp->items = '{"id":"108124505876479","name":"wakeboarding"},{"id":"112003352149145","name":"bouldering"},{"id":"110008522357035","name":"handball"}'; $tmp->save();
found lot of answers, no 1 useful.
update (model file , migration added):
model file:
<?php namespace app; use illuminate\database\eloquent\model; class projects extends model { protected $casts = [ 'items' => 'array', ]; }
migration file:
<?php use illuminate\support\facades\schema; use illuminate\database\schema\blueprint; use illuminate\database\migrations\migration; class createprojectstable extends migration { /** * run migrations. * * @return void */ public function up() { schema::create('projects', function (blueprint $table) { $table->increments('id'); $table->string('gid', 100); $table->string('name', 100); $table->text('items'); $table->timestamps(); }); } /** * reverse migrations. * * @return void */ public function down() { schema::dropifexists('projects'); } }
and function:
$tmp = new projects; $tmp->name = "aaa"; $tmp->gid = "flskjdf3r23r"; $tmp->items = [["id" => "108124505876479", "name" => "wakeboarding"],["id" => "aa", "name" => "volkswagen" ]]; $tmp->save();
i'm assuming projects
class eloquent model. code given, not clear how items
mapped mysql , whether told model want use items
array.
in migration, can set text or json field. e.g.
$table->text('items');
then in model, can declare array:
protected $casts = [ 'items' => 'array', ];
now laravel's eloquent model takes care of mapping array string when gets stored db , vice versa.
as array_merge error, assume set way , eloquent causes error, pass in string.
so can call:
$tmp->items = [["id" => "108124505876479", "name" => "wakeboarding"],["id" => ... ... ]];
see eloquent's casting capabilities: array , json casting
Comments
Post a Comment