Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using touch() to update timestamp of custom timestamp field in laravel

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')));
like image 798
Ronser Avatar asked Dec 22 '14 06:12

Ronser


People also ask

How to update Timestamp in Laravel?

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();

What would this touch () function do in laravel?

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() .

What is the use of timestamps in laravel?

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.

Is used to disable model timestamps in laravel?

Simply place this line in your Model:public $timestamps = false; And that's it!


1 Answers

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.

like image 159
Arvid Avatar answered Nov 15 '22 00:11

Arvid