Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

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.

Comments?