Create URL Slug in Symfony 7

Create URL Slug in Symfony 7

In the web development, constructing clean and search engine-friendly URLs is a crucial aspect of optimizing the application for both users and search engines. Using Unicode characters in URLs is considered unsafe. Symfony provides a String component that can be used to convert a given string into a modified version containing only safe ASCII characters. This tutorial shows how to create URL slug in Symfony 7.

Within a Symfony application, we have the option to inject the SluggerInterface into a service or controller. Utilizing the slug method allows us to convert a provided string into a URL-friendly slug.


namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\String\Slugger\SluggerInterface;

class TestController
    public function index(SluggerInterface $slugger): Response
        $slug = $slugger->slug('публікація в блозі');

        return new Response($slug); // publikacia-v-blozi

Leave a Comment

Cancel reply

Your email address will not be published.