PHP code example of pavelpaliy / eloquent-sluggable
1. Go to this page and download the library: Download pavelpaliy/eloquent-sluggable library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
pavelpaliy / eloquent-sluggable example snippets
use Cviebrock\EloquentSluggable\Sluggable;
class Post extends Model
{
use Sluggable;
/**
* Return the sluggable configuration array for this model.
*
* @return array
*/
public function sluggable(): array
{
return [
'slug' => [
'source' => 'title'
]
];
}
}
$post = Post::create([
'title' => 'My Awesome Blog Post',
]);
echo $post->slug;
$post = Post::create([
'title' => 'My Awesome Blog Post',
]);
// $post->slug is "my-awesome-blog-post"
$newPost = $post->replicate();
// $newPost->slug is "my-awesome-blog-post-1"
use \Cviebrock\EloquentSluggable\Services\SlugService;
$slug = SlugService::createSlug(Post::class, 'slug', 'My First Post');
$slug = SlugService::createSlug(Post::class, 'slug', 'My First Post', ['unique' => false]);
public function sluggable(): array
{
return [
'slug' => [
'source' => ['title', 'id']
]
];
}
public function sluggableEvent(): string
{
/**
* Default behaviour -- generate slug before model is saved.
*/
return SluggableObserver::SAVING;
/**
* Optional behaviour -- generate slug after model is saved.
* This will likely become the new default in the next major release.
*/
return SluggableObserver::SAVED;
}
Post::registerModelEvent('slugging', static function($post) {
if ($post->someCondition()) {
// the model won't be slugged
return false;
}
});
Post::registerModelEvent('slugged', static function($post) {
Log::info('Post slugged: ' . $post->getSlug());
});
public function sluggable(): array
{
return ['slug'];
}
> /**
> * Your trait where you collect your common Sluggable extension methods
> */
> class MySluggableTrait {
> public function customizeSlugEngine(...) {}
> public function scopeWithUniqueSlugConstraints(...) {}
> // etc.
> }
>
> /**
> * Your model
> */
> class MyModel {
> // Tell PHP to use your methods instead of the packages:
> use Sluggable,
> MySluggableTrait {
> MySluggableTrait::customizeSlugEngine insteadof Sluggable;
> MySluggableTrait::scopeWithUniqueSlugConstraints insteadof Sluggable;
> }
>
> // ...
> }
>