Beginner’s Guide to Laravel: Slugs, don’t say eew

Beginner’s Guide to Laravel: Slugs, don’t say eew

In Laravel, a "slug" is a user-friendly URL segment that is typically derived from a string such as a title or name. Slugs are used to create more readable and SEO-friendly URLs for resources like articles, blog posts, or other content. Slugs often replace spaces and special characters with hyphens and are generally in lowercase.

For example, consider the title "Introduction to Laravel CRUD" – the corresponding slug might be "introduction-to-laravel-crud". This slug can be used in URLs, making them more descriptive and human-readable.

Implementing slugs in Laravel involves generating slugs from strings and using them in your routes, controllers, and database queries. If you are following this series, you know that in the last blog post, we built a post management system. If you need a quick recap of that, please follow this link since we will be following that example in this post explanation. Here's how to implement slugs for the "Post" model in your CRUD example.

Generate Slugs

To generate slugs, you can use the Laravel Str::slug helper method. In your Post model's boot method, you can define an event listener that automatically generates a slug when a new post is created:

use Illuminate\Support\Str;

protected static function boot()
{
    parent::boot();

    static::creating(function ($post) {
        $post->slug = Str::slug($post->title);
    });
}

This code listens for the creating event and generates a slug based on the title attribute.

Use Slugs in Routes and Controllers

Modify your routes and controllers to use slugs in URLs. Update the Route::resource definition in routes/web.php to use the {post:slug} parameter:

Route::resource('posts', PostController::class)->parameters([
    'post' => 'post:slug'
]);

Update the show, edit, update, and destroy methods in the PostController to use the Post model loaded by slug instead of ID:

public function show(Post $post)
{
    return view('posts.show', ['post' => $post]);
}
// ...
public function edit(Post $post)
{
    return view('posts.edit', ['post' => $post]);
}
// ...

Modify Blade Views

Update the links in your Blade views to use the slug instead of the post's ID:

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

Similarly, adjust form actions for editing and deleting posts.

By implementing slugs, you enhance the user experience by providing more descriptive and meaningful URLs while maintaining the SEO benefits of clean URLs. Slugs also prevent issues related to duplicate titles in URLs. Just ensure that slugs are unique and handle edge cases like title changes and special characters properly. Happy coding, and enjoy your Laravel journey