brakkar's avatar

Default value of a field used as model $cast

Hi, on a model I have a field 'home_filtering_settings' which is used in a $cast as:

    protected $casts = [
        'email_verified_at' => 'datetime',
        'home_filtering_settings' => AsArrayObject::class,
    ];

For some reason, it will not work if the initial value in the db is empty.

Here is how I use it:

        $currentUser->home_filtering_settings[ 'category-setting' ] = $categorySelectedId;

For this to work I must manually set in the db the content of home_filtering_settings to [].

But if I try to set this default value from migration:

$table->json('home_filtering_settings')->default('[]');

it will crash with: SQLSTATE[42000]: Syntax error or access violation: 1101 BLOB, TEXT, GEOMETRY or JSON column 'home_filtering_settings' can't have a default value

My questions are:

  1. What is the appropriate default value for home_filtering_settings ?
  2. How to set it from migration?
0 likes
5 replies
Nakov's avatar

You can add an accessor to return a default value:

public function getHomeFilteringSettingsAttribute()
{
	return $this->attributes['home_filtering_settings'] ?? [];
}

but also in your migration you could try : ->default([]); just as an array not as a string.

brakkar's avatar

@Nakov Thanks I prefer the migration solution, but it Crashes with: " Array to string conversion"

brakkar's avatar

@Nakov No won't work for same reason as above, but I just read that json field can' t have default value in MySQL, so it might be the issue.

brakkar's avatar

Nevermind, I just set field to [] when creating new user and in my seeds.

Please or to participate in this conversation.