json field in laravel migration

To create a JSON field, all we need to do in Laravel migration is use ->json() method:

Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->decimal('price', 15, 2);
    $table->json('properties');
    $table->timestamps();
    $table->softDeletes();
});

Next, we need to tell our model to cast that column from JSON to an array automatically:

protected $casts = [
        'properties' => 'array'
    ];

To avoid that, we need to eliminate null values from the array. I will use Eloquent mutator feature and transform the array to the one without empty values in app/Product.php model:

public function setPropertiesAttribute($value)
{
    $properties = [];

    foreach ($value as $array_item) {
        if (!is_null($array_item['key'])) {
            $properties[] = $array_item;
        }
    }

    $this->attributes['properties'] = json_encode($properties);
}


Leave a Reply