Mutator doesnt work with arrays, only string #3298
-
| Not sure if this is bug or I just need to type cast Works on string   protected function someAttribute(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => $value,
            set: fn ($value) => 'test'
        );
    }Doesnt work, when save it omits the field name and use an index key,   protected function someAttribute(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => $value,
            set: fn ($value) => ['test']
        );
    }
    Result Even if I add protected cast to array it makes the field name as index number and shows same result | 
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            masterbater
          
      
      
        Mar 6, 2025 
      
    
    Replies: 1 comment 1 reply
-
| Laravel applies  If you want to return an array, you have to wrap the array with the field name:   protected function someAttribute(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => $value,
            set: fn ($value) => ['someAttribute' => ['test']],
        );
    }
     | 
Beta Was this translation helpful? Give feedback.
                  
                    1 reply
                  
                
            
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
Thanks for digging the source code 🙏
Its also in the docs which I have reviewed if this behavior is documented and its there, set array ignores the method to be used as field or column and can set multiple attribute
Each key in the array should correspond with an underlying attribute / database column associated with the model:
https://laravel.com/docs/12.x/eloquent-mutators#mutating-multiple-attributes