Skip to content

Instantly share code, notes, and snippets.

@ericamigo
Created March 3, 2025 04:54
Show Gist options
  • Save ericamigo/7a38fc526026ebe471384f2120095f68 to your computer and use it in GitHub Desktop.
Save ericamigo/7a38fc526026ebe471384f2120095f68 to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
use App\Enums\Types\ActivityType;
use App\Models\Activity;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
trait HasActivities
{
/**
* Relationship Methods
*/
public function activities(): MorphMany
{
return $this->morphMany(Activity::class, 'model');
}
public function firstSentActivity(): MorphOne
{
return $this->morphOne(Activity::class, 'model')
->where('type', ActivityType::Sent);
}
public function lastSentActivity(): MorphOne
{
return $this->morphOne(Activity::class, 'model')
->where('type', ActivityType::Sent)
->latest();
}
public function internalNotes(): MorphMany
{
return $this->morphMany(Activity::class, 'model')
->where('type', ActivityType::InternalNote);
}
/**
* Unsorted Methods
*/
public function record(ActivityType $type, mixed $details = null, ?object $creator = null): Activity
{
return $this->activities()
->create([
'type' => $type,
'details' => $details,
'creator_id' => $creator?->id,
]);
}
public function internalNote(string $note): Activity
{
return $this->record(ActivityType::InternalNote, $note);
}
public function recordChanges(array $original, array $changes): ?Activity
{
if (count($changes) === 0) {
return null;
}
$mappedChanges = [];
foreach ($changes as $attribute => $value) {
if (in_array($attribute, ['updated_at'])) {
continue;
}
array_push($mappedChanges, [
'attribute' => $attribute,
'old' => isset($original[$attribute]) ? $original[$attribute] : null,
'new' => $value,
]);
}
return $this->record(ActivityType::Changes, [
'changes' => $mappedChanges,
]);
}
}

Comments are disabled for this gist.