Changing Case

Convert strings to title, camel, snake, kebab and studly case.

Syntax\Illuminate\Support\Str::snake('helloWorld');

Laravel ships helpers for every common case style:

  • Str::title() — Title Case.
  • Str::camel() — camelCase.
  • Str::snake() — snake_case.
  • Str::kebab() — kebab-case.
  • Str::studly() — StudlyCase.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A REST API normalises incoming field names to camelCase with Str::camel() before mapping them to model attributes, regardless of the client's naming convention.
  • A code-generator converts a human-readable resource name like 'user profile' into the correct file-naming formats: snake_case for migrations and StudlyCase for class names.
  • A search index converts all stored tags to lower-case with Str::lower() before comparison so 'PHP' and 'php' match the same tag.

More examples

Convert between common case styles

Shows four case-conversion helpers applied to the same snake_case string, demonstrating the difference between each output.

Example · php
use Illuminate\Support\Str;

$input = 'user_profile_settings';

Str::camel($input);   // 'userProfileSettings'
Str::studly($input);  // 'UserProfileSettings'
Str::title($input);   // 'User_profile_settings'  (title-cases words)
Str::headline($input); // 'User Profile Settings'

Snake and kebab case

Converts a StudlyCase class name to snake_case and kebab-case — the formats used by database columns and URL slugs.

Example · php
use Illuminate\Support\Str;

$class = 'UserProfileSettings';

Str::snake($class);   // 'user_profile_settings'
Str::kebab($class);   // 'user-profile-settings'
Str::lower($class);   // 'userprofilesettings'
Str::upper($class);   // 'USERPROFILESETTINGS'

Normalise API field names dynamically

Combines Collection::mapWithKeys() and Str::camel() to convert every snake_case key in an API payload to camelCase.

Example · php
$incoming = ['first_name' => 'Alice', 'last_name' => 'Smith'];

$normalised = collect($incoming)
    ->mapWithKeys(fn($v, $k) => [Str::camel($k) => $v])
    ->all();
// => ['firstName' => 'Alice', 'lastName' => 'Smith']

Discussion

  • Be the first to comment on this lesson.