Return of Collection after Update

Asked

Viewed 274 times

0

By default Laravel returns true or false when doing an update.

Example:

User::find(1)->update(['name'=> 'David']);

The return of this will be a true or false, making me need to do another Find to get the User Collection.

Is there any way that the return of this update will be the updated Collection itself?

2 answers

2

The statement of the question is wrong. find does not return Collection, returns the Model.

And it’s easy to solve the problem if you’re using a variable and saving the result of the query in it.

Behold:

$user = User::find(1);

$user->update(...);

dd($user); // Valor atualizado

With the invention of function tap in the newer versions of Laravel, you could do so:

return tap(User::find(1))->update([
    'name' => $name,
    'age' => $age,
]);

Now, if your question is regarding update that is returned from Query Builder, you really need to do another query, since the update is not done on top of each Collection item, but directly in the database.

Example:

 $query = User::where(['x' => 'y']);

 $query->update(['z' => 'x']);

 $users = $query->get();
  • 1

    Excellent Wallace, thank you very much! I learned a lot from your reply!

1


There is nothing prepared by Framework Laravel but, there is how to make a method to solve the update problem and then return the collection with Query Scope:

Within your class User create a method:

public function scopeUpdateGetCollection($query, $id, $data)
{
    $model = $query->find($id);
    if ($model)
    {
        if ($model->update($data))
        {
            return $model->get();
        }
    }
    return null;
}

and use as follows:

$collection = User::updateGetCollection(1, ['name'=> 'David']);

in this particular case a method was made which is responsible for salvar the updates and after mostrar a coleção existing in your table.

Other examples:

Reference: Laravel - Eloquent Query Scopes

  • 1

    Excellent Virgilio! That really solves the problem! Another alternative I just thought of is not to use the Model directly for this and rather the repository, and implement it in the way you suggested as well. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.