DEV Community 👩‍💻👨‍💻


Posted on

Same string, different output... how Laravel's slug & snake helpers differ


Str::slug('PHP') === Str::snake('PHP');

// False

Str::slug('php') === Str::snake('php');

// True
Enter fullscreen mode Exit fullscreen mode

At face value both Str::slug and Str::snake seem to have a similar purpose and are simple to use, given a string they convert it to their respective formats.

use Illuminate\Support\Str;


// php


// php
Enter fullscreen mode Exit fullscreen mode

You'd therefore think that given the same single word string both methods would consistently produce similar outputs, each in their respective formats. However lets see what happens if that string contains uppercase characters.


// php


// p_h_p
Enter fullscreen mode Exit fullscreen mode

These two methods aren't that similar after all, as uppercase characters result in a separator character being added when using Str::snake.

Both Str::slug and Str::snake do allow you to specify which character is used as the separator, so maybe if we specify what separator is to be used things will become more consistent.

Str::slug('PHP', '_');

// php

Str::snake('PHP', '-');

// p-h-p
Enter fullscreen mode Exit fullscreen mode

It's the same behaviour there as well, Str::snake still uses the separator character even when we provide the slug separator (dash) as the parameter. Likewise Str::slug doesn't use the custom separator even though the snake separator (underscore) was given as the parameter.

Now we know the Str::snake method is actually case sensitive, which could be very import when making comparisons or converting from one format to another.

$input = $request->input('programming_language');

Str::snake('php') === Str::snake($input);

// True when $input === 'php'
// False if $input === 'PHP'

$input = Str::lower($request->input('programming_language'));

Str::snake('php') === Str::snake($input);

// True if $input === 'php' or 'PHP'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

19 Valuable Github Repositories for Beginners

19 Valuable GitHub Repositories for beginner devs looking to take the first step into the web development career.