Eloquent Touch for Models in Laravel
Today I want to show you two tricks while working with Laravel. Probably you will know one of them, but might not know the other one.
In this post, we will look at how we can use the eloquent touch feature in Laravel and update the timestamps without updating the model record.
I want to show you two tricks while working with Laravel. Probably you will know one of them but might not know the other one. So, you know there are fields created_at
and updated_at
in Eloquent tables, right? The first trick is we can update them even without updating any data in the row.
It can be useful if you want to save, for example, last time the record was processed during action in your app. See the code below.
$user = User::find(1); $user->touch();
It will actually update only updated_at
column with the current timestamp, without touching any other field.
There’s a second trick, as I promised. You can also touch relationships by providing their names in Eloquent Model properties.
See the code below for an example.
namespace App; use Illuminate\Database\Eloquent\Model; class Comment extends Model { protected $touches = ['post']; public function post() { return $this->belongsTo('App\Post'); } }
See the array called $touches
. This is where you put all the relationships you want to get updated_at
as soon as this Model is updated. So, for example:
$comment = Comment::find(1); $comment->text = 'Edit to this comment!'; $comment->save();
In this case related Post
row for this comment will get a new updated_at
value. This is really really useful if one entity has a lot of child relationships and you want to get its updated time without checking all children relationship updates.
I want to encourage you to sometimes read the source of the inner side of Laravel.
There’s a lot of hidden gems which are not in the documentation.
For example, this $touches
and other undocumented properties can be found by looking at this file.
Impressive, isn’t it?