Laravel Eloquent - $fillable is not working?

后端 未结 4 757
天涯浪人
天涯浪人 2020-12-11 09:28

I have set the variable $fillable in my model. I wanted to test the update functionality, and I get this error:

SQLSTATE[42S

相关标签:
4条回答
  • 2020-12-11 09:48

    write a parent class

    class BaseModel extends Model
    
    public static function getFillableAttribute(Model $model, $data){
        $array = $model->getFillable();
        $arr = [];
        foreach ($array as $item){
            if( isset($data["$item"])){
                $arr["$item"] = $data["$item"];
            }
        }
        return $arr;
    }
    
    0 讨论(0)
  • 2020-12-11 09:50

    Change following:

    ->update(Input::all());
    

    to this (exclude the _method from the array)

    ->update(Input::except('_method'));
    

    Update:

    Actually following update method is being called from Illuminate\Database\Eloquent\Builder class which is being triggered by _call method of Illuminate\Database\Eloquent\Relations class (because you are calling the update on a relation) and hence the $fillable check is not getting performed and you may use Input::except('_method') as I answered:

    public function update(array $values)
    {
        return $this->query->update($this->addUpdatedAtColumn($values));
    }
    

    If you directly call this on a Model (Not on a relation):

    Positions::find($id)->update(Input::all());
    

    Then this will not happen because fillable check will be performed within Model.php because following update method will be called from Illuminate\Database\Eloquent\Model class:

    public function update(array $attributes = array())
    {
        if ( ! $this->exists)
        {
            return $this->newQuery()->update($attributes);
        }
    
        return $this->fill($attributes)->save();
    }
    
    0 讨论(0)
  • 2020-12-11 09:50

    You could also do this

    $data = request()->all();
    //remove them from the array
    unset($data['_token'],$data['_method']);
    //then
    Client::find($client_id)
            ->positions()
            ->whereId($id)
            ->update($data);
    
    

    This removes the _method and _token from the array

    0 讨论(0)
  • 2020-12-11 10:05

    I experienced this breaking after updating from Laravel 5.2 to 5.4 - I can't find anything in the documentation / migration guide that covers it.

    As covered in this github issue the correct fix/use of Eloquent seems to be:

    Positions::find($id)->fill(Input::all())->save();
    

    To trigger the fillable check by laravel and then perist the changes.

    0 讨论(0)
提交回复
热议问题