Reputation: 706
I need to get an element from the database, but I can not get it by the FIND method, since FIND only finds it by the primaryKey and what I need is not by my primaryKey. So I did like this:
$user = Pac::find($request->pac_id);
$element = query()->where('med_cart', $user->pac_id)->get();
$element->med_obs = $request->med_obs;
$element->save(); // error
Now I need to save this element, however, I can not use the SAVE method, as I believe it is fully connected with FIND and FINDORFAIL (if anyone knows, explain to me which methods I can use the SAVE method).
How can I save them the way I did? Or is there some other way to do it?
Because I need to get the element with a data other than the primaryKey and then save it, then I can not use FIND or FINDORFAIL, I think.
Upvotes: 2
Views: 163
Reputation: 11182
The function ->find()
returns an Eloquent Model
instance and you can then call ->save()
on the model instance.
You're using ->get()
which returns a Collection
.
To update your query (that may target one or more entries) just perform the update statement directly from the QueryBuilder by replacing ->get()
with ->update(['med_obs' => $request->med_obs])
.
Be aware that when doing this you are now using Fluent queries, instead of eloquent. This means that any logic you may have defined in the boot
function of your model is not evaluated.
If you are certain that you only have a single result you can append ->first()
to your query, which will return a Model of the first result that matches your ->where
clause. You can then call ->save()
on it:
$user = Pac::find($request->pac_id);
$element = query()->where('med_cart', $user->pac_id)->first();
$element->med_obs = $request->med_obs;
$element->save();
Upvotes: 5