Introduction

In my previous post on working with nullable fields in Eloquent, I talked about two different approaches to this task. The first being with a base model, and the second via a trait. In that post I concluded that I believed the trait was the better of the two options.

Since that post, I've had a few situations where I needed to use the functionality, and creating the trait by hand as needed was getting to be almost as bad as doing the original empty value check in a mutator.

To that end, I sat down and created a small package to make this functionality readily available between projects and wanted to talk a little about it today.

Laravel Nullable Fields

The package, which can be found on GitHub here, is much more declarative, portable, and feels more Laravel-like than the concept I discussed earlier.

By including the NullableFields trait in your Eloquent model and declaring a $nullable property on the base model, you can define an array of database fields whose empty values should be converted to null before being persisted to the database.

<?php

use Iatstuti\Database\Support\NullableFields;
use Illuminate\Database\Eloquent\Model;

class UserProfile extends Model
{
    use NullableFields;

    protected $nullable = [
        'facebook_profile',
        'twitter_profile',
        'linkedin_profile',
    ];
}

This functionality is made possible by attaching a listener to the model's saving event when booting the trait using the bootTraits method, meaning all you need to do is require the Composer package, import the trait, and declaring the $nullable property.

Now, whenever you are saving your model, the trait will compare the set attributes against the defined fields and if a matching attribute is found to be empty, its value will be set to null, before being persisted to the database.


$profile = UserProfile::first();
$profile->facebook_profile = ' '; // Empty
$profile->twitter_profile = 'michaeldyrynda';
$profile->linkedin_profile = ''; // Empty
$profile->save();

Conclusion

I hope some of you will find some use for this trait in your models. I find it particularly useful when tackling foreign key constraints, where you have not yet set the foreign relationship. Of course, as the example above shows, it will be useful in any place you have nullable fields in your database.

Note, the database field must be configured to allow null values.

More recent versions of MySQL will convert the value to an empty string if the field is not configured to allow null, however, be aware that older versions of MySQL may actually return an error.