Is there a way to use touch()
for updating timestamp of is_online
field in table instead of updating created_at
field in laravel Eloquent ORM
At present I am using
User::where('id',$senderId )->update(array('is_online' => date('Y-m-d H:i:s')));
By default, those pivot tables do not contain timestamps. And Laravel does not try to fill in created _at/updated _at in this situation. You can save the timestamps automatically all you need to do is to add them into migration file, and then define relationship using ->withTimestamps();
Touch touch() is a method offered by eloquent that is used to update the updated_at field on the database table for the given model. For example, if you have a login system and you wanted to update the updated_at field whenever a user logs in (as last login), then you do this by $user->touch() .
Timestamps allows you to automatically record the time of certain events against your entities. This can be used to provide similar behaviour to the timestamps feature in Laravel's Eloquent ORM.
Simply place this line in your Model:public $timestamps = false; And that's it!
No, the touch method isn't written for updating anything other than the built in timestamps, but you could write your own function in your User Model, if you want to. Something like this
class User extends Eloquent implements UserInterface, RemindableInterface {
public function touchOnline()
{
$this->is_online = $this->freshTimestamp();
return $this->save();
}
}
and then do replace your old code with
User::find($senderId)->touchOnline();
A few more lines of code, but maybe a slight bit more readable.
You can find the code behind the touch function here, if you're curious.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With