devondahon's avatar

Eloquent: how to create() with json among other values ?

How to set a json field when using adding an entry to a database with create() ?

I tried this:

$i = MyModel::create([
    'foo_id' => $r->foo,
    'bar_id' => $r->bar,
    'data' => json_encode([
        'abc' => $r->my_value,
    ]),
    'created_at' => $r->created_at,
]);

But, it's storing the data like a sting:

data: ""{\"abc\":123}""
0 likes
5 replies
MohamedTammam's avatar

JSON is a string format, so yeah that what it should do.

But it you want to use that field as a normal object in your application, I recommend to use Accessors & Mutators: https://laravel.com/docs/8.x/eloquent-mutators#accessors-and-mutators

In your model

// To set the value
public function setDataAttribute($value){
	$this->attributes['data'] = json_encode($value);
}
// To get the value
public function setDataAttribute($value){
	return json_decode($this->attributes['data']);
}

In your controller.

$i = MyModel::create([
    'foo_id' => $r->foo,
    'bar_id' => $r->bar,
    'data' => [
        'abc' => $r->my_value,
    ],
    'created_at' => $r->created_at,
]);
Tray2's avatar

Why are you wanting to store something as json? There are almost no good reason for it at all.

devondahon's avatar

@tray2 I'm storing a small tree structures not needed by requests. If there were no good reason for using it, why does it exists ?

Tray2's avatar

@devondahon That is the $10000 question.

I think it's because a lot of data is transported like that from different apis and it's a good idea to store the payload from an api before starting to process it. Just like there is an option to store xml in a column.

I'm not saying that it isn't sometimes useful to store json in the database just that it should only store more or less static data that you don't update or search for.

Please or to participate in this conversation.