Last active
June 6, 2023 15:01
-
-
Save danpalmieri/251c696ac046f54ca622ae3664d800ae to your computer and use it in GitHub Desktop.
Enhanced Laravel Trait for Auto-populating the 'slug_token' Column
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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