Tuesday, April 4, 2017

Laravel Mutator/Accessor when column name starts with an uppercase character

I'm working with a legacy database.

I'm facing a column named BackDate that contains a not-nullable date. This was not well-designed and now I have some item with 0000-00-00 as BackDate.

I would like to use it as a Carbon, so I created a Model with date mutator on this column but when this date is "null", I got a wrong Carbon object (build from the string "0000-00-00").

So I had an idea: let's use a custom accessor to check if the date is "null" before creating Carbon object.

public function getBackDate($backDate)
{
    if($backDate == '0000-00-00') return null;
    return new Carbon\Carbon($backDate);
}

But in this case, it doesn't work because, I'm guessing, Laravel lowercase the first letter of BackDate, returning null as $backDate original value (because it doesn't exists).

How can I achieve this issue?



via alberto-bottarini

Advertisement