Laravel 11 - How to Generate Slug

Touseef Afridi
16 Sep 24

Laravel 11 - How to Generate Slug

In this tutorial, we will cover how to generate a slug in Laravel 11. We’ll explore how to use Laravel’s Str class to create URL-friendly slugs from given titles.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through building a simple slug generator in Laravel. We begin by setting up a fresh Laravel project configured with MySQL and Pest. After navigating to the project directory, we customize the default welcome page with a form that accepts a blog title and displays the generated slug. Routes are added to handle the form submission and use Laravel’s Str helper to create the slug. Finally, we start the Laravel server and test the functionality in the browser, with optional notes for saving slugs to the database. This beginner-friendly tutorial is a great starting point for learning how to handle form input, route logic, and dynamic data display in Laravel.

Step # 1 : Set Up the Laravel Project.

Start by creating a new Laravel application or use an existing one. If Laravel is installed globally, you can run.
laravel new slug
Alternatively, you can use Composer by running the command.
composer create-project laravel/laravel --prefer-dist slug
During the setup process, make the following selections to match our development stack.
  • Choose None when prompted for the Starter Kit.
  • Select Pest as the testing framework.
  • Pick MySQL as the database.
  • When asked to run default migrations, type yes.

This will set up a clean Laravel project named slug, tailored to our needs, with Pest for testing and MySQL configured as the database. With this foundation in place, you’ll be ready to start building and testing your slug generator functionality right away, using a modern and efficient development environment.

Step # 2 : Navigate to the Project Directory.

To begin working with your Laravel project, open a terminal (such as Git Bash) and move into the project’s root directory. This allows you to run Artisan commands, serve the app, and manage development tasks. Example command for Git Bash.
cd c:xampp/htdocs/slug
Make sure to adjust the path based on where your Laravel project is located on your local machine, as the directory path may vary depending on where you saved the project.

Step # 3: Customize the Welcome Page.

In this step, we’ll replace the default Laravel welcome page with a simple form that allows users to enter a blog title and generate a slug. This gives us a basic interface to test our slug generation functionality. Open the resources/views/welcome.blade.php file and replace its contents with the following code.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Slug - Code Shotcut</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
    <h1 class="mb-4">Generate Slug - Code Shotcut</h1>
    <form method="POST" action="{{ url('/slug') }}">
        @csrf
        <div class="form-group">
            <label for="title">Blog Title:</label>
            <input type="text" id="title" name="title" class="form-control" value="{{ $title ?? '' }}">
        </div>
        <button type="submit" class="btn btn-primary">Generate Slug</button>
    </form>
    @if(isset($slug))
        <div class="mt-4">
            <h2>Title :</h2>
            <p><strong>{{ $title }}</strong></p>
            <h2>Generated Slug :</h2>
            <p><strong>{{ $slug }}</strong></p>
        </div>
    @endif
</div>
</body>
</html>
This simple form captures a blog title, submits it to the backend, and displays the original title along with its generated slug when available. The form uses the POST method to submit the blog title to the /slug route, where the title is processed, and a slug is generated using Laravel’s Str::slug() helper. If a slug is generated, it is displayed below the form along with the original blog title, allowing users to quickly view the result. This setup provides a great foundation to build upon, enabling easy testing and future enhancements, such as validating input or adding dynamic slug generation for other parts of your application.

Step # 4: Define Routes for the Slug Generator.

Now we’ll define two routes. One for displaying the form and another for handling the form submission. We’ll also use Laravel’s Str helper to generate a slug from the blog title and pass the result back to the view. Open the routes/web.php file and add the following code.
//Import Str and Request classes.
use Illuminate\Support\Str;
use Illuminate\Http\Request;
// To return a view
Route::get('/', function () {
    return view('welcome');
});
//To create a slug
Route::post('/slug', function (Request $request) {
 // Retrieve the title from the request
    $title = $request->input('title');
    // Generate a slug from the title
    $slug = Str::slug($title);
    return view('welcome', ['title' => $title, 'slug' => $slug]);
});
This setup defines two essential routes in web.php one for rendering the form and another for processing the submitted data. The GET route returns the welcome view, while the POST route takes the inputted blog title, generates a slug using Str::slug(), and returns the same view with both the title and slug. This enables users to see their generated slug immediately after submitting the form, creating a smooth and user-friendly experience.

Step # 5 : It's time to test.

With everything set up, it's time to test the slug generator in action. Start the Laravel development server using the following command.
php artisan serve
Once the server is running, open your browser and visit: 127.0.0.1:8000.
You should see a simple form displayed on the page, allowing you to enter a blog title and submit it to generate its corresponding slug. Once submitted, the page will reload and display both the original title and the generated slug, giving you immediate feedback on the slug generation process.


Note: If you want to store the generated slug in the database, you’ll need to update your database schema by adding a slug column to the relevant table typically something like posts or blogs. This can be done by creating a new migration using Laravel’s schema builder. When creating a new blog post, you can generate the slug from the title and save it alongside other post data. Additionally, if the blog title is ever updated, be sure to regenerate the slug to keep it consistent and SEO-friendly. This helps maintain clean, descriptive URLs that reflect the most current title of your content.

Conclusion

By following this guide, you've successfully built a simple slug generator in Laravel. You've set up a fresh project, customized the welcome page with a form, and used Laravel’s Str helper to generate slugs from blog titles. This basic implementation demonstrates how to handle form submissions, process input, and display results on the same page. Moving forward, you can expand this functionality by adding more features such as input validation or further UI improvements. You can also integrate this slug generation logic into your blog creation workflows to streamline URL handling.
For more details, please refer to the Laravel documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering