Laravel Slugs - Generating and Using Slugs for Clean URLs

By Priyash Patil | 3 min read | Updated: Apr 23, 2023 6PM UTC

What is a Slug?

A slug is a user-friendly URL segment that represents a page on a website. It is usually generated from the title of the page and contains only alphanumeric characters, hyphens, and underscores. Slugs are used to create cleaner and more readable URLs, which can improve a website’s search engine ranking and make it easier for users to navigate the site.

Generating a Slug in Laravel

In Laravel, generating a slug is a relatively simple process. Laravel provides a IlluminateSupportStr::slug helper function that can be used to generate a slug from a string. Here’s an example:

use IlluminateSupportStr;

$title = 'Laravel Slugs: Generating and Using Slugs for Clean URLs';
$slug = Str::slug($title);

The Str::slug() function converts the string to lowercase, removes any non-alphanumeric characters, and replaces spaces with hyphens. The resulting slug would be laravel-slugs-generating-and-using-slugs-for-clean-urls.

Spatie Laravel Sluggable Package

As you know generating a slug is very simple in Laravel. However, configuring and extending the slug feature by yourself can be time-consuming. For this post, I’m going to use the package laravel-sluggable by Spatie. Spatie is a well-known developer in the Laravel Community.

Installation and configuration

You can install the package via Composer:

composer require spatie/laravel-sluggable

Your Eloquent models should use the SpatieSluggableHasSlug trait and the SpatieSluggableSlugOptions class. The trait contains an abstract method getSlugOptions() that you must implement yourself. Your models’ migrations should have a field to save the generated slug to.

Here’s an example of how to implement the trait:

namespace App;

use SpatieSluggableHasSlug;
use SpatieSluggableSlugOptions;
use IlluminateDatabaseEloquentModel;

class Post extends Model
{
    use HasSlug;

    /**
	 * Get the options for generating the slug.
	 */
    public function getSlugOptions() : SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('title')
            ->saveSlugsTo('slug');
    }
}

With its migration:

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
  
return new class extends Migration {    
	public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('slug'); // Field name same as your `saveSlugsTo`
            $table->string('title');
            $table->timestamps();
        });
    }
}

You can add more configurations like when or whether to create or update the slug by customising the slug generation.

Using Slugs in Laravel

Using Slugs in Models:

You can also use slugs in Laravel models to make it easier to retrieve records based on their slugs. Here’s an example:

class Post extends Model
{
    public function getRouteKeyName()
    {
        return 'slug';
    }
}

This method overrides the default getRouteKeyName() method in the Laravel Model class and returns the name of the column that should be used to retrieve records based on their slugs. In this case, it returns the slug column.

Using Slugs in Routes:

Once you have generated a slug for a page, you can use it in Laravel routes to create clean and readable URLs. Here’s an example:

// web.php
Route::get('/blog/{post}', 'BlogController@show')->name('blog.show');

// BlogController@show method
public function show(Request $request, Post $post) {
	// The post is automatically retrieved using 
	// Route Model Binding by slug as key.
}

This route will match any URL that starts with /blog/ and has a slug as its second segment. The BlogController@show method will be called to handle the request, and the slug parameter will be passed to the method.

Using Slugs in Views:

Finally, you can use slugs in Laravel views to create links to pages with clean and readable URLs. Here’s an example:

<a href="{{ route('blog.show', $post->slug) }}">{{ $post->title }}</a>

This link will point to the page with the slug that is stored in the $post->slug attribute. The route() function will generate the URL based on the blog.show route and the slug parameter.

Conclusion

Using slugs is a simple and effective way to create clean and SEO-friendly URLs in Laravel. By generating slugs from page titles and using them in routes, models, and views, you can make your website more user-friendly and improve its search engine ranking. Hopefully, this blog post has provided some helpful tips for generating and using slugs in Laravel.

Keep the Conversation Going

I hope you found this post helpful! If you have any questions or feedback, feel free to reach out. You can also find me on X (Twitter) @priyashpatil for additional insights and updates on my latest content.

Related

Featured on laravel-news.com and benjamincrozat.com.

Optimized image uploads with CKEditor and Laravel

By Priyash Patil on Friday, 03 November 2023

Bootstrap 5 Remove Unused CSS with Vite and PurgeCSS

By Priyash Patil on Wednesday, 17 January 2024

Laravel Vite Deploy Assets to Global CDN

By Priyash Patil on Friday, 19 January 2024

Laravel file upload with validation example

By Priyash Patil on Thursday, 25 January 2024