Delta9Tango's avatar

Mutator breaks factory?

I have a client model with a mutator:

    public function setCompanyNameAttribute($value)
    {
        return strtoupper($value);
    }

And a factory

$factory->define(Client::class, function (Faker $faker) {
   return [
        'company_name' => $faker->company,
        'first_name' => $faker->firstName,
        'last_name' => $faker->lastName,
        'primary_phone` => $faker->phoneNumber,
    ];
});

When the factory is called, I do not receive the company_name as an attribute:

            $client = factory(Client::class)->make();
dd($client);

----- 
#attributes: array:3 [
    "first_name" => "Anna"
    "last_name" => "Mills"
    "primary_phone" => "334-717-4998"
  ]

When I remove the mutator, all 4 attributes are present:

  #attributes: array:4 [
    "company_name" => "Weissnat, Hilpert and Osinski"
    "first_name" => "Jaylon"
    "last_name" => "Quitzon"
    "primary_phone" => "602-948-8484"
  ]

I added protected $fillable = ['company_name'] and have no $guarded but the company_name still doesn't show in the attributes list.

Is this a known issue, or do I need to add something else to my client model? Most of my tests broke with the addition of the mutator.

(edit: markdown...)

0 likes
4 replies
Erutan409's avatar

@Swaz Interesting, thank you. I'd expect that it would mutate the attribute based on what you'd return from the mutator. Also looks like they're going the Attribute class route in the later versions, too. Although this is still valid; for now.

Thank you.

Cronix's avatar

Did you copy/paste that code?

'primary_phone` => $faker->phoneNumber,

the end quote on primary_phone is wrong...

Delta9Tango's avatar

@Swaz I see now. I read through the docs too quickly and assumed the mutator was the same as the accessor. I knew another set of eyes would point me in the correct direction.

@Cronix Yes, copy/paste. The original source has correct quotes.

Please or to participate in this conversation.