using touch() to update timestamp of custom timestamp field in laravel
19,390
Solution 1
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.
Solution 2
Laravel 4.2
class User extends Eloquent implements UserInterface, RemindableInterface
{
public static function boot()
{
parent::boot();
/*
static::creating(function($table) {
$table->foo = 'Bar';
});
*/
static::updating(function($table) {
$table->is_online = $this->freshTimestamp();
// $table->something_else = 'The thing';
});
}
}
Usage. Just call the native touch method.
User::find($senderId)->touch();
Author by
Ronser
I'll try something if it dosen't works I'll try something else but I'll keep on trying...
Updated on June 23, 2022Comments
-
Ronser almost 2 years
Is there a way to use
touch()
for updating timestamp ofis_online
field in table instead of updatingcreated_at
field in laravelEloquent ORM
At present I am using
User::where('id',$senderId )->update(array('is_online' => date('Y-m-d H:i:s')));
-
Arvid over 9 yearsNo, if anything I'd guess probably slower. But then again touch is probably also slower than updating the created_at or updated_at manually in the same way you're doing.
-
Arvid over 9 yearsBut the main reason we're using Laravel isn't speed (there are far speedier frameworks) - it's probably readability and ease of use. And in that respect I think my proposition is better. But if you're doing the update really often I understand if you want to go the more raw way :)
-
Arvid over 8 yearsYou should be aware the
touch()
call will also update theupdated_at
column. And, more importantly, theupdating
event listener introduced will also refresh theis_online
anytime the model is updated for some reason. When it's triggered by the user editing her details that's probably fine, but if the update is because the admin is editing the a user it is probably undesired behavior. -
Everton Z. P. over 7 years@Arvid Well noted! Maybe we can do some verification before call
User::find($senderId)->touch();
, for example not execute when the admin is editing or something like that.