Eloquent push() and save() difference

Heres the magic behind the scenes…

/**
 * Save the model and all of its relationships.
 *
 * @return bool
 */
public function push()
{
    if ( ! $this->save()) return false;

    // To sync all of the relationships to the database, we will simply spin through
    // the relationships and save each model via this "push" method, which allows
    // us to recurse into all of these nested relations for the model instance.

    foreach ($this->relations as $models)
    {
        foreach (Collection::make($models) as $model)
        {
            if ( ! $model->push()) return false;
        }
    }

    return true;
}

It just shows that push() will update all the models related to the model in question, so if you change any of the relationships, then call push()
It will update that model, and all its relations
Like so…

$user = User::find(32);
$user->name = "TestUser";
$user->state = "Texas";
$user->location->address = "123 test address"; //This line is a pre-defined relationship

If here you just…

$user->save();

Then the address wont be saved into the address model….
But if you..

$user->push();

Then it will save all the data, and also save the address into the address table/model, because you defined that relationship in the User model.

push() will also update all the updated_at timestamps of all related models of whatever user/model you push()

Hopefully that will clear the things….

Leave a Comment