Search code examples
laravellaravel-5.5polymorphic-associationslaravel-auditing

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 \OwenIt\Auditing\Auditable;
   use SoftDeletes;

}
class Customer extends Model implements Auditable
{
   use \OwenIt\Auditing\Auditable;
   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 \OwenIt\Auditing\Auditable;
   use SoftDeletes;

} 

Currently I use something like this to retrieve audits:

$staff = App\Model\Staff::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.


Solution

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