Reputation: 1095
Imagine that you have a model User related with many roles, where the roles are also shared by other users.
User model also have an updated_at field on the database that is updated to current time when any field of User is updated. If User's name changes, its updated_at field changes too.
What should happen if you just change User related roles? Should you update the updated_at field or not?
If so, there's any way to update this field automatically when updating the related roles of a User?
public function update(Request $request, $id)
{
...
$user->update($data);
$roles = $user->roles()->sync($request->get('roles'));
if (!empty($roles['attached']) ||
!empty($roles['detached'])) { // <!-- Is there a better way to check these conditions?
$user->touch();
}
}
Upvotes: 2
Views: 332
Reputation: 111889
What you can do is adding into Role
model the following property:
protected $touches = ['user'];
You need to also have the following relationship:
public function user()
{
return $this->belongsToMany(User::class);
}
This way, when you attach or detach roles for users each time updated_at
field will be updated for those users.
Be aware that this will also be used when you only update Role model - in case you update it, automatically updated_at
column will be updated for users that has this role assigned.
EDIT
Sorry, I've missed the part you asking whether you should do it. In my opinion - rather not. In updated_at
you should rather hold when the direct object has been updated. I could understand it in case you have for example User model and for each User you have also Profile model. In this case updating Profile model could cause updating timestamp for User model but in this case I wouldn't use that. You can use timestamps fields in pivot table if you need and in case you need to keep some history of changes, I would rather create dedicated solution for that to hold dates of changes of related models with User rather than simply updating updated_at
each time anything related will be attached/detached/updated. But of course everything depends on application demands. Probably there might be some cases that it would be a good solution but at the moment I cannot think any.
Reference: Touching parent timestamps
Upvotes: 2
Reputation: 2214
There's no technical reason why you should (or should not) update the related updated_at
timestamps. It entirely depends on what makes most sense for your application.
Updating related timestamps automatically
Laravel supports a $touches
property on the model (docs):
class Role extends Model
{
/**
* All of the relationships to be touched.
*
* @var array
*/
protected $touches = ['users'];
/**
* Get the users that have this role.
*/
public function users()
{
return $this->belongsToMany('App\User');
}
}
Updating timestamps manually
If you just want to set updated_at
to the current time, use the $user->touch()
method, as you suggest in the question.
Upvotes: 1