The new take() method to form substrings in Laravel
Laravel has this method called substr()
(both in Illuminate\Support\Str
classes and str()
global helper) which is used to form substrings from a given string.
Here’s how you can use it.
use Illuminate\Support\Str;
Str::substr('Memento Mori', 0, 7);
// Memento
str('Memento Mori')->substr(0, 7);
// Memento
As you can tell, the method is not very intuitive when you just want to form a substring from the beginning or end of the string. You have to pass the starting index as 0
and the length of the substring as 7
to form a substring from the beginning of the string.
This is where the new take()
method comes in. It’s a new method that’s been added to the Str
class and the str()
global helper in Laravel 8.x.
Here’s how you can use it.
use Illuminate\Support\Str;
Str::take('Memento Mori', 7);
// Memento
str('Memento Mori')->take(7);
// Memento
As you can tell, the take()
method is much more intuitive and easier to use than the substr()
method.
You can also pass a negative number to the take()
method to form a substring from the end of the string.
use Illuminate\Support\Str;
Str::take('Memento Mori', -4);
// Mori
I think this is a great little addition to the ever-growing Laravel helper methods.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.