简体   繁体   中英

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?

I noticed that the function name is incorrect, since the accessors use "studly" cased name of the column you wish to access, it may be as simple as to change

public function setFirstNameAttribute($value)

to

public function setCompanyIdAttribute($value)

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM