Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bigweld86's avatar

Laravel mutator not converting null into empty string

I'm running an integration test and am getting the following error:

array:5 [ "message" => "Argument 1 passed to App\Models\Order::getPhoneAttribute() must be of the type string, null given, called in /Users/bigweld/Sites/restaurantbe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 454" "exception" => "Symfony\Component\Debug\Exception\FatalThrowableError" "file" => "/Users/bigweld/Sites/restaurantbe/app/Models/Order.php" "line" => 87 "trace" => array:44 [

So it seems to be related to my mutators, which are:

public function setPhoneAttribute(string $phone) : void
    {
        $this->attributes[self::ORDER_PHONE] = empty($phone) ? "" : preg_replace("/[^A-Za-z0-9 ]/", '', $phone);
    }

    public function getPhoneAttribute(string $phone) : string
    {
        return is_null($phone) ? "": preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~',
            '()--', $phone);
    }

my test is not passing Order::ORDER_PHONE meaning that an empty string should be stored in the database. If I declare the field in the data array along with the other fields even if empty (ie: [ Order::ORDER_PHONE => "" ]) then this error is not coming up.

Any ideas why?

0 likes
6 replies
tisuchi's avatar

@bigweld86

Does phone field in your table nullable? If not, can you make it nullable first and then try with your code?

Nakov's avatar

@bigweld86

or just remove the type check on the accessor

public function getPhoneAttribute($phone) 
bigweld86's avatar

@nakov not an option. I wanna find a better solution instead of starting to remove type hints from all over the place

Nakov's avatar
Nakov
Best Answer
Level 73

@bigweld86

Then make it optional, because you don't have control of the source code. I bet it tries to call the accessor without a parameter

public function getPhoneAttribute(?string $phone)

// or

public function getPhoneAttribute(string $phone = null) 
2 likes
bigweld86's avatar

@nakov the fist one worked! thanks a lot. The second one did not, even though I used:

public function getPhoneAttribute(string $phone ="") 

Please or to participate in this conversation.