Introduction to Stringable::whenNotExactly() in Laravel 11
Hello friends! Today we want to talk about an interesting feature in Laravel 11 related to the Stringable
class and the whenNotExactly
method. Before we dive into the details of this method, let’s get a little more familiar with the concept of Stringable
. This class helps us work with strings in a simpler and more effective way.
In previous versions of Laravel, we usually used various methods for working with strings. However, with the introduction of Stringable
, this task has become much easier. The whenNotExactly
method is one of the utility methods that provides us the ability to perform specific actions based on certain string values.
Now let’s see how whenNotExactly
can be used. This method allows you to check a condition and if the given string does not match a specific value, execute a certain action. This topic is important when we want to ignore certain specific values and look for more complex logical implementations.
You can use this method to simplify your code and make it more readable. Let’s look at a simple example of how to use this method to become more familiar with its functionality.
Example Implementation of using whenNotExactly
$string = Str::of('Laravel 11');
$result = $string->whenNotExactly('Laravel 10', function ($str) {
return $str->append(' is awesome!');
});
echo $result;
Code Explanation
Code:
$string = Str::of('Laravel 11');
This line creates an instance of the
Stringable
class holding the string 'Laravel 11'
.Code:
$result = $string->whenNotExactly('Laravel 10', function ($str) {...});
In this line, the
whenNotExactly
method is called. If the string $string
does not equal 'Laravel 10'
, the specified action will be executed.Code:
return $str->append(' is awesome!');
This line adds the string
' is awesome!'
to the string $str
.Code:
echo $result;
In the end, the result gets printed. In this case, the output would be
'Laravel 11 is awesome!'
.