aesircloud/sluggable

A Laravel package to automatically generate slugs for models

1.0.5 2024-07-11 18:43 UTC

README

sluggable is a Laravel package that generates unique slugs for Eloquent models. It can be used to automatically generate slugs when creating or updating models.

Installation

You can install the package via composer:

composer require aesircloud/sluggable

Publish the configuration file

php artisan vendor:publish --provider="AesirCloud\Sluggable\SluggableServiceProvider"

Usage

To use the package, add the Sluggable trait to your Eloquent model and optionally define the $slugSource property to configure the slug generation, the default value is name:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use AesirCloud\Sluggable\Traits\Sluggable;

class Post extends Model
{
    use Sluggable;

    protected $fillable = ['title', 'slug'];

    protected $slugSource = 'title'; // or 'description', or any other field
}

You will need to add a slug column to your table. You can do this by creating a migration:

php artisan make:migration add_slug_to_posts_table --table=posts
    <?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('slug')->unique()->after('title');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('slug');
        });
    }
};

Changelog

Please see CHANGELOG for more information what has changed recently.

Security

If you've found a bug regarding security please mail security@aesircloud.com instead of using the issue tracker.

License

The MIT License (MIT). Please see License File for more information.