tuDEV's avatar
Level 1

What exactly is a slug?

str_slug()

The str_slug function generates a URL friendly "slug" from the given string:

$title = str_slug('Laravel 5 Framework', '-');

// laravel-5-framework

I was looking through the documentation, perhaps not hard enough, but I'm just trying to understand what exactly a slug is and what it's used for. Thanks!

0 likes
9 replies
Jaytee's avatar

Slugs serve a variety of purposes. In their basic form, they're useful for:

  1. Friendly URLs. Also plays well with SEO
  2. They can also serve as a unique identifier to a resource.
  3. They can be used to mask ID's from your database table. For example, if you didn't want to expose the id of an article, e.g: /articles/1, you could use a slug instead /articles/this-is-my-article

EDIT: Apologies for bumping this thread. It appears Laracasts has had an update to the date/time, and since i'm in a timezone +12/13, it's playing up with my feed.

2 likes
nezmah's avatar

Furthermore, slug() takes care of unwanted characters - does some sanitization. This is a definition of slug():

  /**
     * Generate a URL friendly "slug" from a given string.
     *
     * @param  string  $title
     * @param  string  $separator
     * @param  string|null  $language
     * @return string
     */
public static function slug($title, $separator = '-', $language = 'en')
    {
        $title = $language ? static::ascii($title, $language) : $title;

        // Convert all dashes/underscores into separator
        $flip = $separator === '-' ? '_' : '-';

        $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);

        // Replace @ with the word 'at'
        $title = str_replace('@', $separator.'at'.$separator, $title);

        // Remove all characters that are not the separator, letters, numbers, or whitespace.
        $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title));

        // Replace all separator characters and whitespace by a single separator
        $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);

        return trim($title, $separator);
    }

from: Illuminate\Support\Str\slug()

Please or to participate in this conversation.