Skip to content

Commit

Permalink
Added the ability to pass a callback to when creating the model
Browse files Browse the repository at this point in the history
  • Loading branch information
luisdalmolin committed Nov 30, 2024
1 parent 3d18bb9 commit 7f2901a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,18 @@ class Commenter extends NovaCommenter

Then use this class instead of the default `Commenter` class within your resources.

### Customizing the comment

By default, the `Comment` model will strip tags from the comment body. If you would like to modify this behavior, you can pass an callback to the `Comment::whenCreating` method. This callback will receive the comment model instance as a parameter.

```php
Comment::whenCreating(function (Comment $comment) {
$comment->comment = strip_tags($comment->comment);
});
```

```php

## Changelog

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
Expand Down
30 changes: 24 additions & 6 deletions src/Models/Comment.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace KirschbaumDevelopment\NovaComments\Models;

use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
Expand All @@ -17,20 +18,29 @@ class Comment extends Model
*/
protected $table = 'nova_comments';

/**
* @var Closure|callable|null
*/
protected static $whenCreating = null;

/**
* The "booting" method of the model.
*/
public static function boot(): void
{
parent::boot();

static::creating(
function ($comment): void {
if (auth()->check()) {
$comment->commenter_id = auth()->id();
}
static::creating(function ($comment): void {
if (auth()->check()) {
$comment->commenter_id = auth()->id();
}

if (static::$whenCreating) {
call_user_func(static::$whenCreating, $comment);
} else {
$comment->comment = strip_tags($comment->comment);
}
);
});
}

/**
Expand All @@ -48,4 +58,12 @@ public function commenter(): BelongsTo
{
return $this->belongsTo(config('auth.providers.users.model'), 'commenter_id');
}

/**
* @param Closure|callable $callback
*/
public static function whenCreating($callback): void
{
static::$whenCreating = $callback;
}
}

0 comments on commit 7f2901a

Please sign in to comment.