Laravel Eloquent ignore attribute if not in table during insert

前端 未结 4 1440
不思量自难忘°
不思量自难忘° 2021-02-19 03:44

I have a model Foo that corresponds to a table with the following columns.

id
description
user_id

I\'m setting the attributes of the Foo model individual

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 04:24

    I understand this question is old but it was in top results for a recent search where I was trying to solve a similar problem and I think that this may be an ideal case for Laravel accessors/mutators. I have tested this on Laravel 5.6 but believe it may work as far back as 4.2.

    By creating a mutator and accessor rather than a public property it will allow adding the field to fillable for mass assignment while still excluding it from the internal attributes (thus preventing it from errantly saving to the DB). I understand the original request excluded mass-assignment but that doesn't necessarily exclude this answer. I think an example will help:

    class Foo extends Model
    {
        //Allow bar in mass assignment
        protected $fillable = [
                "bar"
            ];
    
        /**
         * Store bar in protected variable instead of attributes
         * Because bar is not set in attributes, Laravel will not try to save it to database
         */
        protected $bar;
    
        /**
         * Mutator method to set bar's value
         */
        public function setBarAttribute($value)
        {
            $this->bar = $value;
        }
    
        /**
         * Accessor method to retrieve bar's value
         */ 
        public function getBarAttribute()
        {
            return $this->bar;
        }
    }
    

    When this model is created using mass-assignment the mutator (setBarAttribute) method will be called for bar if it exists in the mass-assigned values. Anytime the bar property is accessed the respective get/set method will be called. Because the mutator does not set the value of bar in the model's internal attributes variable the model will not save bar to the database.

提交回复
热议问题