Get DevTools for Tailwind CSS with full JIT engine support directly in your browser Learn more

Go back to Blog

The magic of the Laravel str() helper

Sebastian Schlein

As a Laravel developer, we are used to work with helpers across the framework and our own code. They provide an abstraction layer to existing PHP functions and make them easier to use.

Why the abstraction is needed? PHP still has many legacy functions that aren't as easy to use as their helper counterparts. If you've ever added arguments to a PHP function and ordered them wrongly, you know what I mean – it's not consistent and the abstraction layer fixes this.

There are other functions – like substr() that many people use without knowing that there is a better one that can also deal with multibyte characters: mb_substr(). So if you want to get the first character of a last name and this is an 'Ö', you'll better use mb_substr().

Why is this related to Laravel helpers?

Laravel helpers wrap these functions and provide a fluent interface to interact with them. This means that someone else already run into the issue and Laravel uses mb_substr under the hood if you use the str() helper.

  substr('Öllandschaft', 0, 1);          // b"Ã"
  mb_substr('Öllandschaft', 0, 1);       // "Ö"
  str('Öllandschaft')->substr(0, 1);     // "Ö"

It simply puts you on the save side and also improves readability.

Using the str() helper without an application context

As soon as you leverage a tool like Tinkerwell, you can use these helpers in other scenarions, even if you don't implement a feature in an application right now. The Laravel str() helpers can create UUIDs, reverse Strings, create slugs and much more.

Tinkerwell with helpers

str()->explode()

Another good example of a str helper is explode. The explode helper for strings in Laravel is not simply a wrapper around the normal explode function of PHP but also returns a collection instead of an array. This allows you to use the collection magic directly on a string.

str('How many words has this String?')
    ->explode(' ')
    ->count(); 

// 6

str('Lorem ipsum dolor sit amet')
    ->explode(' ')
    ->take(3)
    ->join(' '); 

// Lorem ipsum dolor

Laravel helpers are everywhere in the Laravel codebase and using them in your own application makes your code easier to understand. The helpers solve common issues and when using them via the str() helper, you don't even need an import statement for them.

Its time to Tinkerwell

The must-have tinker tool for every PHP and Laravel developer. This magical desktop app may not be able to fly. But when it comes to PHP code, it sure knows how to run.

Learn more