a-dev-coder-f's avatar

Mass Assignment of Json Columns via Wildcards

How can I allow mass assignment of a json field with wildcards instead of directly defining all the keys in the Fillable array?

I know that I can set nested json data if I use the fillable field, where 1, 2 = the order id. However, it's not practical to assign every single nested json dynamic value in the fillable array.

// This works for the exact nested values set. 
// Model
class Book {
	protected $fillable = [
		'related',
		'related->order'
		'related->order->1',
		'related->order->2',    
	]
}

// Some update file elsewhere

$orderID = 1;

$book->update([
	"related->order->$orderID" => $orderID
]);

However, wildcard values like

// Model
	protected $fillable = [
		'related',
		'related->order'
		'related->order->*'
	]

// Update file
$orderID = 5;

// Fails, nothing gets updated. The field, 'related->order->5` remains the same in the db json
$book->update([
	"related->order->$orderID" => $orderID
]);

Was this even possible besides using forceFill?

ie

// Model, nothing fillable set

// Update code
$orderID = 5;

// Works now
$book->forceFill([
	"related->order->$orderID" => $orderID
]);
$book->save();

I need this as setting a dynamic order $key->val update will override existingrelated->order values when I just want to append them.

0 likes
2 replies
Tray2's avatar

The easiest it to just

protected $guarded = [];

However I really don't recommend using json in you database, you should create a good database model for your application instead.

I suggest giving this one a read, https://tray2.se/posts/database-design

1 like
a-dev-coder-f's avatar

@Tray2 Alas, the db is set and there's no changing that.

I still want to use the fillable field to protect the rest of my fields, I have a singular field in the example to make it readable.

I might just opt for force fill, at least that way I can prevent mass assignment whilst being able to directly set the json fields.

Please or to participate in this conversation.