PHP code example of jetcod / laravel-slugify

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

    

jetcod / laravel-slugify example snippets


use Jetcod\LaravelSlugify\SlugOptions;
use Jetcod\LaravelSlugify\Traits\HasSlug;

class YourModel extends Model
{
    use HasSlug;

    protected $casts = [
        'slugs' => 'array', // Optional: Cast the 'slugs' attribute to an array
    ];

    protected $sluggables = ['a_column_name'];  // Specify columns to be sluggified

    protected function getSlugConfig(): SlugOptions
    {
        return SlugOptions::create()
            ->slugColumn('slugs')   // Define the column name where the slugs will be stored
        ;
    }
}

$post = new Post();
$post->title = "This is an Example Title";
$post->save();

// $post->slugs will be like {"title":"this-is-an-example-title"} (based on the configured options)

use Jetcod\LaravelSlugify\SlugOptions;
use Jetcod\LaravelSlugify\Traits\HasSlug;

class YourModel extends Model
{
    use HasSlug;

    protected $sluggables = ['title'];

    protected function getSlugConfig(): SlugOptions
    {
        return SlugOptions::create()
            ->slugColumn('slugs')
            ->avoidDuplicates()
        ;
    }
}

$post = new Post();
$post->title = "This is an Example Title";
$post->save();

// Result: $post->slugs will be like {"title":"this-is-an-example-title"} 

// Create another post with the same title
$post = new Post();
$post->title = "This is an Example Title";
$post->save();

// Result: $post->slugs will be like {"title":"this-is-an-example-title-1"}