Enhancing Your URLs with Eloquent-Sluggable in Laravel
When building web applications, user-friendly URLs play a significant role in improving both user experience and SEO performance. Instead of relying on cryptic IDs, clean and readable slugs can make your URLs more intuitive and memorable. In Laravel, the Eloquent-Sluggable package provides a powerful and flexible way to generate slugs automatically from your model attributes.
In this blog, we’ll explore what Eloquent-Sluggable is, how to install and configure it, and the various ways you can use it to enhance your Laravel projects.
What is Eloquent-Sluggable?
Eloquent-Sluggable is a Laravel package that automatically creates slugs for Eloquent models. A slug is a simplified version of a string, typically derived from titles or names, that can be used in URLs. For instance, the title “How to Use Laravel” might be turned into the slug “how-to-use-laravel.”
The package takes care of generating, storing, and ensuring the uniqueness of these slugs, making it a convenient tool for any Laravel developer.
Features of Eloquent-Sluggable:
Automatic Slug Generation:
Automatically generate slugs from any specified attribute of your model.
Customizable Slugs:
Customize the slug generation process, including the separator, maximum length, and whether the slug should be unique.
Handling Duplicates:
The package automatically ensures that each slug is unique by appending a number to duplicates.
Easily Re-Sluggable:
You can easily update or regenerate slugs when the source attribute changes.
Slug Scoping:
Limit the uniqueness of slugs within specific scopes, such as by user or category.
Installing Eloquent-Sluggable
Getting started with Eloquent-Sluggable is straightforward. First, let’s install the package using Composer:
composer require cviebrock/eloquent-sluggable
After installing the package, publish the configuration file to your Laravel application:
php artisan vendor:publish --provider="Cviebrock\EloquentSluggable\ServiceProvider"
This command will create a config/sluggable.php file where you can define the default settings for your slugs.
Using Eloquent-Sluggable in Your Models
To start using Eloquent-Sluggable in your models, you’ll need to make a few simple modifications.
Add the Sluggable Trait:
In your model, add the Sluggable trait provided by the package:
class Post extends Model { use Sluggable; public function sluggable(): array { return [ 'slug' => [ 'source' => 'title' ] ]; } }
In this example, the slug will be generated from the title attribute.
Create a Slug Column:
Ensure that your model’s table has a column to store the slug. You can add this through a migration:
Copy codephp artisan make:migration add_slug_to_posts_table --table=posts
Then, add the following in your migration file:
public function up() { Schema::table('posts', function (Blueprint $table) { $table->string('slug')->unique(); }); }
Run the migration to update your database:
php artisan migrate
Generating Slugs:
- With the trait added and the migration run, slugs will now automatically generate when you create or update a Post
-
$post = new Post(); $post->title = 'My First Blog Post'; $post->save(); echo $post->slug; // Outputs "my-first-blog-post"
Customizing Slug Behavior
Eloquent-Sluggable is highly customizable, allowing you to tailor slug generation to your specific needs.
Customizing the Slug Source
You can customize the source of the slug to be a combination of multiple attributes:
public function sluggable(): array { return [ 'slug' => [ 'source' => ['title', 'subtitle'] ] ]; }
Changing the Separator
By default, slugs are separated by hyphens (-), but you can change this to any character:
public function sluggable(): array { return [ 'slug' => [ 'source' => 'title', 'separator' => '_' ] ]; }
This will generate slugs like my_first_blog_post.
Limiting Slug Length
You can also limit the maximum length of the slug:
php Copy codepublic function sluggable(): array { return [ 'slug' => [ 'source' => 'title', 'maxLength' => 50 ] ]; }
Slugging on Update
By default, slugs are only generated when a model is first created. However, you can enable slugging on updates by setting the onUpdate option to true:
public function sluggable(): array { return [ 'slug' => [ 'source' => 'title', 'onUpdate' => true ] ]; }
Handling Duplicate Slugs
Eloquent-Sluggable automatically ensures slug uniqueness by appending a number to duplicates:
// First post $post1 = Post::create(['title' => 'My Blog Post']); // Outputs "my-blog-post" // Second post with the same title $post2 = Post::create(['title' => 'My Blog Post']); // Outputs "my-blog-post-1"
Querying with Slugs
Eloquent-Sluggable also provides handy methods for querying models by their slugs. For instance, you can use the findBySlug method:
$post = Post::findBySlug('my-first-blog-post');
Or, if you want to ensure that a model is found or throw a ModelNotFoundException, use findBySlugOrFail:
$post = Post::findBySlugOrFail('my-first-blog-post');
Conclusion
Eloquent-Sluggable is an incredibly useful package for Laravel developers who want to generate clean, SEO-friendly URLs effortlessly. With its rich feature set and customizable options, it can be tailored to fit any project’s needs.
Whether you’re building a blog, an e-commerce platform, or any other web application, integrating Eloquent-Sluggable into your Laravel models will make your URLs more user-friendly and improve your site’s overall search engine ranking.