Michael Dyrynda
Home Blog Podcasts
Working with nullable field in Eloquent models - Part Deux June 18th, 2015


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.

3use Iatstuti\Database\Support\NullableFields;
4use Illuminate\Database\Eloquent\Model;
6class UserProfile extends Model
8 use NullableFields;
10 protected $nullable = [
11 'facebook_profile',
12 'twitter_profile',
13 'linkedin_profile',
14 ];

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.

1$profile = UserProfile::first();
2$profile->facebook_profile = ' '; // Empty
3$profile->twitter_profile = 'michaeldyrynda';
4$profile->linkedin_profile = ''; // Empty


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.

I'm a real developer ™
Michael Dyrynda


I am a software developer specialising in PHP and the Laravel Framework, and a freelancer, blogger, and podcaster by night.

Proudly hosted with Vultr

Syntax highlighting by Torchlight