generated from spatie/package-skeleton-laravel
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathHasSlugAttributeTrait.php
70 lines (61 loc) · 1.87 KB
/
HasSlugAttributeTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
namespace Statikbe\FilamentFlexibleContentBlocks\Models\Concerns;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Statikbe\FilamentFlexibleContentBlocks\Events\SlugChanged;
/**
* @property string $slug
*/
trait HasSlugAttributeTrait
{
use HasSlug;
public function initializeHasSlugAttributeTrait(): void
{
$this->mergeFillable(['slug']);
}
protected static function bootHasSlugAttributeTrait(): void
{
//dispatch event when slug changes for published models:
static::updating(function (self $record) {
$newSlug = $record->slug;
$existingSlug = $record->getOriginal('slug');
$changedSlugs = [];
if ($newSlug !== $existingSlug) {
$changedSlugs[] = [
'locale' => app()->getLocale(),
'oldSlug' => $existingSlug,
'newSlug' => $newSlug,
];
}
if (! empty($changedSlugs)) {
$published = true;
if (method_exists($record, 'isPublishedForDates')) {
$published = $record->isPublishedForDates($record->getOriginal('publishing_begins_at'), $record->getOriginal('publishing_ends_at'));
}
//dispatch event:
SlugChanged::dispatch($record, $changedSlugs, $published);
}
});
}
/**
* Get the options for generating the slug.
*
* @property string|null $slug
*/
public function getSlugOptions(): SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug')
->doNotGenerateSlugsOnUpdate();
}
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
}