DEV Community

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

Posted on

10

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! 😗 🧀

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay