paxha / laravel-sluggable
This package provides an event that will generate a unique slug when saving or creating any Eloquent model.
Installs: 4 011
Dependents: 2
Suggesters: 0
Security: 0
Stars: 2
Watchers: 2
Forks: 2
Open Issues: 0
Type:laravel
Requires
- php: ^7.2|^8.0
Requires (Dev)
- orchestra/testbench-dusk: ^4.0
- phpunit/phpunit: ^8.0
This package is auto-updated.
Last update: 2024-12-18 00:58:06 UTC
README
Laravel Slug Generator
Introduction
This package provides an event that will generate a unique slug when saving or creating any Eloquent model.
Installation
composer require paxha/laravel-sluggable
Usage
Getting Started
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 '_'; } }
Examples
Example A
Database
Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('first_name'); $table->string('last_name'); $table->string('slug')->unique(); });
Model
class User extends Model { use \Sluggable\Traits\Sluggable; protected $fillable = [ 'first_name', 'last_name', ]; public static function slugFrom() { return ['first_name', 'last_name']; } }
Create User
User::create([ 'first_name' => 'John', 'last_name' => 'Doe' ]); // or $user = new User(); $user->first_name = 'John'; $user->last_name = 'Doe'; $user->save();
Output
{ 'first_name': 'John', 'last_name': 'Doe', 'slug': 'john-doe', }
Example B
Table
Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('user_slug')->unique(); });
Model
class User extends Model { use \Sluggable\Traits\Sluggable; protected $fillable = [ 'name', ]; public static function slugSaveTo() { return ['user_slug']; } public static function separator() { return '_'; } }
Create User
User::create([ 'name' => 'John Doe' ]); // or $user = new User(); $user->name = 'John Doe'; $user->save();
Output
{ 'name': 'John Doe', 'user_slug': 'john_doe', }
License
This is open-sourced laravel library licensed under the MIT license.