As we all know, the PHP empty string '' can be interpreted in a few ways that result in some ambiguities.
Right now I'm handling input from a form that contains some float (as defined in my laravel migration) values.
I suppose there are two angles to this issue. One is that Input::get (and all variants) is returning empty text fields as '' as opposed to null. That may or may not be a problem depending on how you look at it.
What might be an issue if this isn't, is that a double quote empty string is not being caught by Eloquent and getting converted to a proper null. So when I insert the value into the database, in my case I'm getting 0.000000 instead of null. And yes, the field is flagged as nullable :)
This is not Laravel's problem. Input::get does return null when the key wasn't specified, but if it is, it returns its value. If that value happens to be empty, your application has to act on that.
Same for the Eloquent part. If you tell the model to set the value to an empty string, it will do so. You are the one to assure that you set proper values.
So, for the Input::get, I can see that. There's some interpretation required.
For Eloquent, because it doesn't hold a schema in memory, alright, it's just passing values through.
So here's the rub now: I tried to implement __get() on my model so that when I try to fill values, I can sanitize them for certain properties. Unfortunately, using fill() seems to bypass the dynamic setter being called and so I miss my last opportunity to catch the data being put into the class.
If I have to do this in the controller, I risk lots of code duplication (and fattening) every time I want to update values which should be "true-null".
That's where Eloquent getters and setters come in:
public function setFloatAttribute($value)
{
$this->attributes['float'] = (float) $value ?: null;
}
Those will be called for fill().
Alright, that works for me, thanks!
Most helpful comment
That's where Eloquent getters and setters come in:
Those will be called for
fill().