DEV Community

Cover image for Using Laravel push method to update your model and its relationships
Matheus Lopes Santos
Matheus Lopes Santos

Posted on

Using Laravel push method to update your model and its relationships

Today's tip is about a method that I've seen a few people talking about. It's a model method called push.

"But what does this method do, Matheusão?"

Let's imagine the following scenario:

$user = User::with('address')->first();

$user->name = 'Matheusão';
$user->address->country = 'Brazil';

$user->save();
$user->address()->save();
Enter fullscreen mode Exit fullscreen mode

Awesome! We've retrieved the user with his address and updated his name and country.

However, we can use the pushmethod that will save everything for us:

$user = User::with('address')->first();

$user->name = 'Matheusão';
$user->address->country = 'Brazil';

$user->push();
Enter fullscreen mode Exit fullscreen mode

This simple command will save our model data and iterate over its relations and save all the new data for us.

And another great thing: If we update a relationship inside another relationship, it will be saved too!

Let's take a look at the push method definition:

public function push()
{
    if (! $this->save()) {
        return false;
    }

    foreach ($this->relations as $models) {
        $models = $models instanceof Collection
            ? $models->all() : [$models];

        foreach (array_filter($models) as $model) {
            if (! $model->push()) {
                return false;
            }
        }
    }

    return true;
}
Enter fullscreen mode Exit fullscreen mode

As we can see, every time that script iterates over a relation, it calls the push method again, allowing us to save a lot of relations recursively.

But don't forget to put this kind of operation inside a transaction to avoid data loss.

$user = User::with('address')->first();

$user->name = 'Matheusão';
$user->address->country = 'Brazil';

\DB::transaction(fn () => $user->push());
Enter fullscreen mode Exit fullscreen mode

That's all, folks, keep coding! 😗 🧀

Top comments (0)