Laravel String Helper Function: slug

November 16, 2016 —John Koster

The slug helper method will format the given $title to resemble a URI slug. It does this through a series of steps:

  • Convert the $title to ASCII formatting (using the ascii function);
  • Converts whitespace, dashes, underscores to the $separator;
  • Reduces whitespace and separators to a single character, and trims the whitespace and separators from the beginning and end of the string.

The signature for the slug helper method is:

slug($title, $separator = '-')

This function will also convert the entire string to its lower cased alternative.

1use Illuminate\Support\Str;
2 
3// laravel-ninja
4echo Str::slug('laravel ninja');
5 
6// laravel-ninja
7echo Str::slug(' laravel ninja ');
8 
9// laravel-nin-ja
10echo Str::slug(' Laravel NIN JA ');
11 
12// laravel-ninja
13echo Str::slug('Laravel - Ninja - ');
14 
15// laravel-ninja
16echo Str::slug('Laravel-_-_Ninja - ');

#str_slug($title, $separator = '_')

The str_slug function is a shortcut to calling Str::slug. This function is declared in the global namespace.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.