Laravel Eloquent Sluggable – Automatically create slugs

Laravel Eloquent Sluggable is a package that simplifies the creation and management of slugs for Eloquent models in Laravel applications. A slug is a URL-friendly version of a string, often used in URLs to identify resources in a readable way.

 

Key Features of Laravel Eloquent Sluggable:

  1. Automatic Slug Generation: Automatically generates slugs from a specified field in your model (e.g., titles).
  2. Customizable Slug Format: Customize the format of the slug to fit your needs.
  3. Unique Slugs: Ensure that generated slugs are unique, avoiding conflicts with existing entries.
  4. Slug Updates: Automatically update slugs when the original field is modified.
  5. Integration with Eloquent: Seamlessly integrates with Laravel’s Eloquent ORM.

 

Installation

To get started with Laravel Eloquent Sluggable, follow these steps:

  1. Require the Package: Install the package via Composer:
  2. Publish the Configuration (optional): You can publish the configuration file using:
  3. Setup the Model: You need to set up your model to use the Sluggable trait. For example, if you have a Post model:
     

Database Migration

Ensure your database migration includes a slug column in your model’s table. For example, for the posts table:

 

Using the Model

Now that the model is set up, you can create a new post, and a slug will be generated automatically based on the title.

  1. Creating a Post: When you create a new post, the slug will be generated from the title:
  2. Updating the Post: If you update the title, the slug will automatically update if you configure it to do so:
     

Custom Slug Format

You can customize the slug format by chaining additional methods in the getSlugOptions method. For example, if you want to add a timestamp to the slug:

 

Conclusion

Laravel Eloquent Sluggable makes managing slugs in your Laravel applications straightforward. By automating the generation and management of slugs, it helps you maintain clean, user-friendly URLs.

 

Additional Considerations

  • Documentation: For more detailed information, advanced features, and configuration options, refer to the official Spatie Eloquent Sluggable documentation.
  • Handling Duplicates: The package can automatically handle slug conflicts by appending a unique suffix (e.g., my-post-1, my-post-2) if configured.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top