Collection Return after Update

0

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

Example:

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

The return of this will be a true or false, causing me to make another Find to pick up the User collection.

Is there any way that the return of this update will be the actual collection updated?

    
asked by anonymous 02.03.2018 / 16:47

2 answers

1

Nothing is done by Framework Laravel but there is a way 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 it as follows:

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

In this specific case, a method was made that is responsible for% with% updates and then salvar in your table.

Other examples :

Laravel - Eloquent Query

Scopes

    
02.03.2018 / 17:30
2

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

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

See:

$user = User::find(1);

$user->update(...);

dd($user); // Valor atualizado

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

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

Now, if your query is in relation to 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 on the database.

Example:

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

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

 $users = $query->get();
    
02.03.2018 / 17:40