ifnicolas / sluggable
A PHP library designed to simplify and automate the creation of URL-friendly slugs based on Laravel. Fork of italofantone/sluggable with Laravel 13 support.
Requires
- php: ^8.1
- illuminate/database: ^10.0|^11.0|^12.0|^13.0
- illuminate/support: ^10.0|^11.0|^12.0|^13.0
Requires (Dev)
- orchestra/testbench: ^8.0|^9.0|^10.0|^11.0
- phpunit/phpunit: ^10.5|^11.3|^12.0
README
A PHP library designed to simplify and automate the creation of URL-friendly slugs based on Laravel.
This package is a fork of italofantone/sluggable by Italo Morales Fantone, updated to support Laravel 13. All credit for the original work goes to him.
Requirements
- PHP 8.1+
- Laravel 10, 11, 12 or 13
Installation
You can install the sluggable package via composer. Run the following command:
composer require ifnicolas/sluggable
Usage
1. Add the trait to your model
To use the Sluggable functionality, include the Sluggable trait in your Eloquent model:
<?php namespace App\Models; use IfNicolas\Sluggable\Sluggable; use Illuminate\Database\Eloquent\Model; class Lesson extends Model { use Sluggable; protected $fillable = ['title', 'body']; }
Migration example: you need to create the slug field.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::create('lessons', function (Blueprint $table) { $table->id(); $table->string('title'); $table->string('slug')->unique(); $table->text('body'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('lessons'); } };
2. Customize the separator
Publish the config file:
php artisan vendor:publish --tag=sluggable-config
Then edit config/sluggable.php:
<?php return [ /** * The separator used when generating slugs. * e.g. 'my title' will be converted to 'my-title'. * * Default: '-'. */ 'separator' => '-', ];
3. Customize the slug source field
By default the slug is generated from the title attribute. You can change this by setting the protected $slugSourceField property in your model:
<?php namespace App\Models; use IfNicolas\Sluggable\Sluggable; use Illuminate\Database\Eloquent\Model; class Lesson extends Model { use Sluggable; protected $fillable = ['name', 'body']; protected $slugSourceField = 'name'; }
With this configuration, the slug will be generated based on the name attribute.
Testing
composer install vendor/bin/phpunit
Credits
- Italo Morales Fantone — original author
- ifNicolas — Laravel 13 compatibility
License
The MIT License (MIT). See LICENSE for more information.