Return to home

Laravel Slugs - Generating and Using Slugs for Clean URLs

By Priyash Patil | Updated: May 14, 2023 6PM IST

SEO is an important aspect to consider when building a website. One way to improve your website’s SEO is by having clean, readable URLs that accurately describe the content of each page. In this blog post, we will explore how to generate and use slugs in Laravel to create clean and SEO-friendly URLs.

Table of contents

  1. What is a Slug?
  2. Generating a Slug in Laravel
    1. Spatie Laravel Sluggable Package
    2. Installation and configuration
  3. Using Slugs in Laravel
  4. Conclusion

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 an Illuminate\Support\Str::slug helper function that can be used to generate a slug from a string. Here’s an example:

use Illuminate\Support\Str;

$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 Laravel Community.

Installation and configuration

You can install the package via composer:

composer require spatie/laravel-sluggable

Your Eloquent models should use the Spatie\Sluggable\HasSlug trait and the Spatie\Sluggable\SlugOptions 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 Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;

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 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('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.