Skip to content

Instantly share code, notes, and snippets.

@danpalmieri
Last active June 6, 2023 15:01
Show Gist options
  • Save danpalmieri/251c696ac046f54ca622ae3664d800ae to your computer and use it in GitHub Desktop.
Save danpalmieri/251c696ac046f54ca622ae3664d800ae to your computer and use it in GitHub Desktop.
Enhanced Laravel Trait for Auto-populating the 'slug_token' Column
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
trait HasSlugToken
{
/**
* The length of the slug.
*
* @var int
*/
public static int $slugLenght = 5;
/**
* The characters to use for the slug.
*
* @var string
*/
public static string $slugCharacters = '23456789abcdefghjmnpqrstuvxzwyk';
/**
* The column name to use for the slug.
*
* @var string
*/
public static string $slugColumn = 'slug_token';
/**
* Boot the trait.
*
* @return void
*/
public static function bootHasSlug(): void
{
static::creating(function (Model $model) {
do {
$model->slug = substr(str_shuffle(self::$slugCharacters), 0, self::$slugLenght);
} while (
get_class($model)::where(self::$slugColumn, $model->slug)->exists()
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment