I have a one to many relationship between Device
and Command
models (each Device
has many commands
). Now I want to update a collection of commands using save()
method. So, I used the following code:
$device = Device::find(1);
$commands = $device->commands()->whereStatus("pending")->get();
$commands->status = "sent";
$commands->save();
But I got a FatalErrorException
exception with an error message of Call to undefined method Illuminate\Database\Eloquent\Collection::save()
.
In other words, I am looking for an equivalent MySQL query of the following in the Eloquent
:
UPDATE commands SET status = 'sent' WHERE status = 'pending';
using Laravel 4.2
You could try the
update
method:Since
$commands
is a collection, changing the value of$commands->status
will not have the effect that you intend (setting the value ofstatus
to 'sent' for every item in the collection).Instead, act on each item in the collection independently:
You can also update the items in the database via Query Builder: