This trait allows you to easily flag attributes that should be set as null when being persisted to the database using the Laravel PHP Framework.

2.0.0 2019-09-06 05:38 UTC



Travis Build Status Scrutinizer Code Quality Code Coverage Latest Stable Version Total Downloads License

Often times, database fields that are not assigned values are defaulted to null. This is particularly important when creating records with foreign key constraints, where the relationship is not yet established.

public function up()
    Schema::create('profile_user', function (Blueprint $table) {

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

Laravel does not currently support automatically setting nullable database fields as null when the value assigned to a given attribute is empty.


This trait is installed via Composer. To install, simply add it to your composer.json file:

$ composer require iatstuti/laravel-nullable-fields

In order to use this trait, import it in your Eloquent model, then set the protected `$nullable` property as an array of fields you would like to be saved as `null` when empty.


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

class UserProfile extends Model
	use NullableFields;
	protected $nullable = [
	protected $casts = [ 'array_casted' => 'array', ];

Now, any time you are saving a UserProfile profile instance, any empty attributes that are set in the $nullable property will be saved as null.


$profile = new UserProfile::find(1);
$profile->facebook_profile = ' '; // Empty, saved as null
$profile->twitter_profile  = 'michaeldyrynda';
$profile->linkedin_profile = '';  // Empty, saved as null
$profile->array_casted = []; // Empty, saved as null
$profile->array_not_casted = []; // Empty, saved as null

More information

Working with nullable fields in Eloquent models - first iteration

Working with nullable fields in Eloquent models - Part Deux - second iteration, covers the details of this package


If you are having general issues with this package, feel free to contact me on Twitter.

If you believe you have found an issue, please report it using the GitHub issue tracker, or better yet, fork the repository and submit a pull request.

If you're using this package, I'd love to hear your thoughts. Thanks!