laravellaravel-5mutators

Laravel Mutator to add predefined values into database


I'm new into Laravel and I'm trying to store the user's company id on a column of the products table each time a user creates a new product. The company's id it's retrieved from the user's session. I'm trying it with Laravel's Mutator:

public function setFirstNameAttribute($value) {
        $this->attributes['company_id'] = session()->get('company.id');
    }

But each time I create a new Product the company id stored it's null. Seems like the function it's never executing. Is there any other resource to perform actions like this?


Solution

  • You must use model events - this will be executed on model creation before saving. Or you can use another events depends on you logic - see docs.

    class YourModel extends Model
    {
        /**
         * The "booted" method of the model.
         *
         * @return void
         */
        protected static function booted()
        {
            static::creating(function (YourModel $model) {
                $model->company_id = session()->get('company.id');
            });
        }
    }
    

    Mutators only works when you change mutating field directly: $model->first_name = 'new_name'

    And with your code - you will lost "new_name".