Using touch () to update the timestamp of a custom timestamp field in laravel

Is there a way to use touch()

to update the timestamp is_online

in the table instead of updating the field created_at

in laravel Eloquent ORM

I am currently using

User::where('id',$senderId )->update(array('is_online' => date('Y-m-d H:i:s')));

      

+3


source to share


3 answers


No, the touch method is not written to update anything other than the built-in timestamps, but you can write your own function in your user model if you like. Something like that

class User extends Eloquent implements UserInterface, RemindableInterface {

    public function touchOnline()
    {
        $this->is_online = $this->freshTimestamp();
        return $this->save();
    }
}

      

and then replace the old code with



User::find($senderId)->touchOnline();

      

A few more lines of code, but maybe a little more readable.

You can find the code behind the touch function here if you're interested.

+6


source


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';
        });
    }
}

      



Use . Just call the native touch method.

User::find($senderId)->touch();

      

0


source


A quick alternative is to override the CREATED_AT constant in your model like

Class User extends Model
{
    protected UPDATED_AT = 'is_online';
}
$user->touch();

      

Just keep touching

0


source







All Articles