Polymorphic Laravel Auditing Package - Retrieving polymorphic audits


Polymorphic Laravel Auditing Package - Retrieving polymorphic audits



I am currently using Laravel Auditing (Owen-it) package to audit models automatically which is working great using the following code.


class Staff extends Model implements Auditable
{
use OwenItAuditingAuditable;
use SoftDeletes;

}
class Customer extends Model implements Auditable
{
use OwenItAuditingAuditable;
use SoftDeletes;

}



Seeing as there is a significant number of fields (> 20) on these classes I am intending to convert these classes to a polymorphic relationship where all common fields reside in the base class and any class unique properties will go in their respective classes.



For example - the base class:


class User extends Model implements Auditable
{
use OwenItAuditingAuditable;
use SoftDeletes;

}



Currently I use something like this to retrieve audits:


$staff = AppModelStaff::find($id);
$allAudits= $staff->audits;



My question is then is there a clean way to retrieve all audits across the base and morphed class?



Thanks in advance.




2 Answers
2



I don't think this is possible by default, since the model's fully qualified name is stored as the auditable_type.


auditable_type



By default, Laravel will use the fully qualified class name to store the type of the related model. For instance, given the example above where a Comment may belong to a Post or a Video, the default commentable_type would be either AppPost or AppVideo, respectively.



You may be able to leverage morphMap, however, to create custom types that encompass the base and inherited classes:


morphMap


use IlluminateDatabaseEloquentRelationsRelation;

Relation::morphMap([
'posts' => 'AppPost',
'videos' => 'AppVideo',
]);



My question is then is there a clean way to retrieve all audits across the base and morphed class?



You could add the following method to your base class in order to fetch all audits:


public function getAllAudits(): Collection
{
return Audit::where(function ($query) {
$query->where('auditable_type', get_class($this))
->where('auditable_id', $this->id);
})
->orWhere(function ($query) {
$morph = $this->userable; // or whatever morph relation name you have set

$query->where('auditable_type', get_class($morph))
->where('auditable_id', $morph->id);
})
->get();
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV