POV
POV

Reputation: 12015

How to update row and return updated_at?

I attempted to update row and return value of updated_at instantly after:

$product = ProductModel::where("Id", $id)->update(["Status" => 0]);

return $product->updated_at;

How to do that correct?

Also can I do this globally for each update?

Upvotes: 1

Views: 1277

Answers (4)

ceejayoz
ceejayoz

Reputation: 180024

The update function is intended to do a bulk update, against however many rows your query returns. It could be zero, it could be one, it could be a thousand. As such, its return value is just a boolean "did it work?" value.

Since you're looking to update a single row:

$product = ProductModel::where("Id", $id)->first();
$product->Status = 0;
$product->save();

return $product->updated_at;

You really should tell Laravel about your custom primary key, so you can use ProductModel::find($id) for cleaner code.

Side note: If you have a single ProductModel in $product, and you use update() on it, you can do $product->refresh() to re-fetch its data from the database.

Upvotes: 4

Hamid Haghdoost
Hamid Haghdoost

Reputation: 867

check out this:

$product = ProductModel::where("Id", $id)->first();
$product->Status = 0;
$product->save();

return $product->updated_at;

Upvotes: 0

Hamid Haghdoost
Hamid Haghdoost

Reputation: 867

The updated_at field will be touched automatically after an update operation and you don't have to do that manually, if you want to touch the updated_at timestamp in other times, use touch() method as following snippet:

$user = User::find(1);
$user->touch();

Upvotes: 2

Arthur Samarcos
Arthur Samarcos

Reputation: 3299

This line of code will return you a boolean. True for a successful update, false for no updates.

$product = ProductModel::where("Id", $id)->update(["Status" => 0]);

Try this:

$product = ProductModel::find($id);

$product->update(["Status" => 0]);

return $product->updated_at;

Upvotes: 1

Related Questions