PHP code example of cviebrock / eloquent-sluggable

1. Go to this page and download the library: Download cviebrock/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/ */

    

cviebrock / 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());
});

return [
    'source'             => null,
    'method'             => null,
    'onUpdate'           => false,
    'separator'          => '-',
    'unique'             => true,
    'uniqueSuffix'       => null,
    'firstUniqueSuffix'  => 2,
    '

public function sluggable(): array
{
    return [
        'title-slug' => [
            'source' => 'title'
        ],
        'author-slug' => [
            'source' => ['author.lastname', 'author.firstname'],
            'separator' => '_'
        ],
    ];
}

class Book extends Eloquent
{
    use Sluggable;

    protected $fillable = ['title'];

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => ['author.name', 'title']
            ]
        ];
    }
    
    public function author(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Author::class);
    }
}
...
class Author extends Eloquent
{
    protected $fillable = ['name'];
}

class Person extends Eloquent
{
    use Sluggable;

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'fullname'
            ]
        ];
    }

    public function getFullnameAttribute(): string
    {
        return $this->firstname . ' ' . $this->lastname;
    }
}

'method' => ['Illuminate\\Support\\Str', 'slug'],

'method' => static function(string $string, string $separator): string {
    return strtolower(preg_replace('/[^a-z]+/i', $separator, $string));
},

$post->slug = null;
$post->update(['title' => 'My New Title']);

'uniqueSuffix' => static function(string $slug, string $separator, Collection $list, $firstSuffix): string
    {
      $size = count($list);

      return chr($size + 96);
    }

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;
>         }
> 
>     // ...
> }
> 

/**
 * @param \Cocur\Slugify\Slugify $engine
 * @param string $attribute
 * @return \Cocur\Slugify\Slugify
 */
public function customizeSlugEngine(Slugify $engine, string $attribute): \Cocur\Slugify\Slugify
{
    // ...
    return $engine;
}

/**
 * @param \Illuminate\Database\Eloquent\Builder $query
 * @param \Illuminate\Database\Eloquent\Model $model
 * @param string $attribute
 * @param array $config
 * @param string $slug
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeWithUniqueSlugConstraints(
    Builder $query,
    Model $model,
    string $attribute,
    array $config,
    string $slug
): Builder
{
    // ...
}

/**
 * Query scope for finding "similar" slugs, used to determine uniqueness.
 *
 * @param \Illuminate\Database\Eloquent\Builder $query
 * @param string $attribute
 * @param array $config
 * @param string $slug
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeFindSimilarSlugs(Builder $query, string $attribute, array $config, string $slug): Builder
{
    // ...
}

$post = Post::whereSlug($slugString)->get();

$post = Post::findBySlug($slugString);

$post = Post::findBySlugOrFail($slugString);
sh
    php artisan vendor:publish --provider="Cviebrock\EloquentSluggable\ServiceProvider"