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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free