Just released! Manage your Laravel projects with Invoker. The no-bull Laravel admin panel.

What Are The Differences Between Update And Fill in Laravel?

Arie Visser • August 18, 2020

laravel php database

When you need to update a resource in Laravel, you might decide to use the update or the fill method.

What are the differences between these methods?

Let's take a look at the source code of the fill and update methods, in Illuminate\Database\Eloquent\Model.

The update and fill methods will only work on attributes that are mass assignable.

The update method:

public function update(array $attributes = [], array $options = [])
{
    if (! $this->exists) {
        return false;
    }

    return $this->fill($attributes)->save($options);
}

The fill method:

public function fill(array $attributes)
{
    $totallyGuarded = $this->totallyGuarded();

    foreach ($this->fillableFromArray($attributes) as $key => $value) {
        $key = $this->removeTableFromKey($key);

        // The developers may choose to place some attributes in the "fillable" array
        // which means only those attributes may be set through mass assignment to
        // the model, and all others will just get ignored for security reasons.
        if ($this->isFillable($key)) {
            $this->setAttribute($key, $value);
        } elseif ($totallyGuarded) {
            throw new MassAssignmentException(sprintf(
                'Add [%s] to fillable property to allow mass assignment on [%s].',
                $key, get_class($this)
            ));
        }
    }

    return $this;
}

As you can see, the update method also calls the fill method. The only difference is that the update method writes the changes to the database afterwards.

What does the fill method do exactly?

After some logical checks if the attribute is "fillable", it will assign the given value from the $attributes array to the model, with the setAttribute method.

The setAttribute method assigns a value to an attribute on the model, after it has checked for any available mutators and attribute casts.

It will not write the assigned values to the database. For this you would have to call the save method manually.

The primary benefit of using the fill method, is that it gives you the ability to assign values to attributes that aren't mass assignable, before calling save. For example, when first_name and last_name of a user are "fillable", and password isn't, you could update the model like this:

$user->fill([
    'first_name' => 'John',
    'last_name' => 'Doe',
]);

$user->password = 'secret'; 

$user->save();