-
app/Helpers/HasAuthor.php
Open in GitHubuse App\Models\User; use Illuminate\Database\Eloquent\Relations\BelongsTo; trait HasAuthor { public function author(): BelongsTo { return $this->creator(); } public function authoredBy(User $author) { $this->creator()->associate($author); } public function creator(): BelongsTo { return $this->belongsTo(User::class, 'author_id'); } public function isAuthoredBy(User $user): bool { return $this->author()->matches($user); } }
-
app/Models/Comment.php
Open in GitHubuse App\Helpers\HasAuthor; use Illuminate\Database\Eloquent\Model; final class Comment extends Model { use HasAuthor; // }
-
app/Jobs/CreateComment.php
Open in GitHubuse App\Models\Comment; use App\Models\User; final class CreateComment { // public function handle(): Comment { $comment = new Comment( [ 'commentable_type' => 'articles', 'commentable_id' => $this->article_id, 'body' => $this->comment, ] ); $comment->authoredBy($this->author); $comment->save(); return $comment; } }