marnixk77's avatar

Attribute causing error when using FirstorCreate

I have a model with the following attribute:

    protected function price(): Attribute
    {
        return Attribute::make(
            get: fn (int $value) => (number_format(($value/100), 2)),
        );
    }

When I retrieve data this works without issues. But when I use the FirstorCreate function with data data doesn't already exists in the table is generates an error: App\Models\PriceHistory::App\Models{closure}(): Argument #1 ($value) must be of type int, null given

Firstorcreate looks like this. I double checked, but al values are filled with data.

 $priceHistory = PriceHistory::firstOrNew(
  [
     'product_id' => $this->pLink->product_id,
     'size_id' => $productSize->id,
     'updated_at' => $today
  ]
  );

If I remove the attribute from the model the firstorcreate works without issue. Why is this not working ?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue you're encountering is likely due to the firstOrNew method attempting to access the price attribute on a model instance that has not yet been saved to the database. Since the price attribute is not set (it's null), the getter method for the price attribute fails because it expects an integer value.

To resolve this issue, you can modify the getter method to handle null values gracefully. Here's how you can update your price attribute getter to return null or a formatted string depending on whether the $value is null or an integer:

protected function price(): Attribute
{
    return Attribute::make(
        get: fn ($value) => is_null($value) ? null : number_format(($value / 100), 2),
    );
}

With this change, if $value is null, the getter will simply return null instead of attempting to format it, which should prevent the error you're seeing when using firstOrNew or firstOrCreate.

Additionally, ensure that the price column in your database allows null values if there are cases where a PriceHistory model might be created without a price. If the price column is not nullable and you're trying to create a PriceHistory without a price, you'll need to provide a default value for it.

2 likes

Please or to participate in this conversation.