This package provides an event that will generate a unique slug when saving or creating any Eloquent model.
composer require paxha/laravel-sluggable
Consider the following table schema for hierarchical data:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
});
Use the Sluggable
trait in your model to work with slug:
class User extends Model
{
use \Sluggable\Traits\Sluggable;
}
By default, the trait expects three things
- slugFrom(): array (optional) if you using
name
column - slugSaveTo(): string (optional) if you using
slug
column - separator(): string (optional) default
-
You can overriding it as well slugFrom()
, slugSaveTo()
and separator()
:
class User extends Model
{
use \Sluggable\Traits\Sluggable;
public static function slugFrom()
{
return ['name']; // or return ['first_name', 'last_name'];
}
public static function slugSaveTo()
{
return 'slug'; // or return ['user_slug'];
}
public static function separator()
{
return '-'; // or return '_';
}
}
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('slug')->unique();
});
class User extends Model
{
use \Sluggable\Traits\Sluggable;
protected $fillable = [
'first_name', 'last_name',
];
public static function slugFrom()
{
return ['first_name', 'last_name'];
}
}
User::create([
'first_name' => 'John',
'last_name' => 'Doe'
]);
// or
$user = new User();
$user->first_name = 'John';
$user->last_name = 'Doe';
$user->save();
{
'first_name': 'John',
'last_name': 'Doe',
'slug': 'john-doe',
}
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('user_slug')->unique();
});
class User extends Model
{
use \Sluggable\Traits\Sluggable;
protected $fillable = [
'name',
];
public static function slugSaveTo()
{
return ['user_slug'];
}
public static function separator()
{
return '_';
}
}
User::create([
'name' => 'John Doe'
]);
// or
$user = new User();
$user->name = 'John Doe';
$user->save();
{
'name': 'John Doe',
'user_slug': 'john_doe',
}
This is open-sourced laravel library licensed under the MIT license.