Support the ongoing development of Laravel.io →
Database Eloquent Architecture

I'm not sure how everyone else does it, but just wanted to get some thoughts (and cleanup) on how I've been converting empty strings to null in an effort to make MySQL yell at the user.

I have a top level, abstract ModelObserver that does the following. I've stripped out all irrelevant code.

abstract class ModelObserver {

	public function saving($model)
	{
		$values = $model->attributesToArray();

		array_walk($values, function(&$value)
		{
			$value = $this->emptyToNull($value);
		});

		foreach($values as $attribute => $value)
		{
			$model->{$attribute} = $value;
		}
	}

	private function emptyToNull($string)
	{
		if (trim($string) === '')
			$string = null;

		return $string;
	}
}
Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

sajanp sajanp Joined 18 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.