Editable Laravel One-To-Many Models

Is it possible for the editable to track changes in one-to-many relationships? For instance:

Model: User. Model: Messages. User model uses Venturecraft \ Revisionable \ RevisionableTrait; and have hasMany related to messages. If a message has been added or updated, is it possible to track this using an audit under the user who owns the message?

Thank you in advance

+6
source share
1 answer

I was able to come up with something. However, this is not the most elegant solution, so it would be great if someone helped me clean it (especially this uncomfortably bothers me).

My solution will create duplicates in the table to which the model belongs. I don't know if that was what you wanted.

The first thing you need to do is add a column with a zero datetime revision_at value to the appropriate table.

The trait itself is pretty simple. We use the boot() model method to register updating models. It will fire whenever the model is about to update. This is exactly what we need, because we do not want a review when creating the model for the first time.

 <?php trait RevisionableTrait { public static function boot() { parent::boot(); static::updating(function( $model ){ // Grab the original Model and unset the id // from it, so that we don't get duplicate // entries when we create a new model. $attributes = $model->getOriginal(); unset( $attributes['id'] ); // Next we need to add the date the revision // was created $attributes['revision_at'] = new DateTime(); $revision = new static($attributes); $revision->save(); }); } } 

The only thing we do here is to capture the original model before assigning new fields, turn off the identifier to make sure that we are not creating a duplicate record, set the current time for the revision_at field and save the model.

What is it basically.

can this be tracked by auditing under the user who owns the message?

This is done automatically, as the new revision model still belongs to the corresponding user,

If you want to fine-tune it, you can create a dedicated table for revisions where the model link is stored. However, saving properties can become a little more complicated (perhaps you can save them in serialized form). A.

Another possible improvement would be to change the getter methods of the model in the attribute. For example, let all() return only models that are not revisions. Then add the withRevisions() method to capture them. You can extract logic from it if you look at how Laravel handles Soft Deletes. This is exactly the same.

+1
source

Source: https://habr.com/ru/post/978792/


All Articles