How to upper or lowercase a string in Laravel
In Laravel, we can use the Str class provided by the PHP framework to convert a string to its uppercase or lowercase form. The Str class offers convenient methods for string manipulation, including upper and lower helper methods.
The upper helper method
The upper helper method returns the uppercase variant of the given string. The basic structure of the upper helper method is as follows:
<?phppublic static function upper(string $value);
This method is helpful when performing invariant string comparisons or modifying content to display to an end user and when we need to ensure that a string is uppercased. The following example provides a practical example of upper helper method by returning all the uppercased strings.
cGhwOgogIHByZXNldDogbGFyYXZlbAogIHZlcnNpb246IDgKICBkaXNhYmxlZDoKICAgIC0gbm9fdW51c2VkX2ltcG9ydHMKICBmaW5kZXI6CiAgICBub3QtbmFtZToKICAgICAgLSBpbmRleC5waHAKICAgICAgLSBzZXJ2ZXIucGhwCmpzOgogIGZpbmRlcjoKICAgIG5vdC1uYW1lOgogICAgICAtIHdlYnBhY2subWl4LmpzCmNzczogdHJ1ZQo=
Code explanation
One line 15, we use the upper helper method from the Str class to convert all the characters of the given strings to their uppercase variants. Using fluent strings is another way of calling the upper helper method on strings. Fluent strings are used on lines 18–19 to uppercase the characters of the given strings.
The lower helper method
The lower helper method takes a string and returns its lowercase variant. The lower method will use the UTF-8 character encoding when converting the string to its lowercase equivalent. The basic structure of a lower helper method is as follows:
<?phppublic static function lower(string $value);
The following example provides a practical example of the lower helper method by returning all the lowercase strings.
cGhwOgogIHByZXNldDogbGFyYXZlbAogIHZlcnNpb246IDgKICBkaXNhYmxlZDoKICAgIC0gbm9fdW51c2VkX2ltcG9ydHMKICBmaW5kZXI6CiAgICBub3QtbmFtZToKICAgICAgLSBpbmRleC5waHAKICAgICAgLSBzZXJ2ZXIucGhwCmpzOgogIGZpbmRlcjoKICAgIG5vdC1uYW1lOgogICAgICAtIHdlYnBhY2subWl4LmpzCmNzczogdHJ1ZQo=
Code explanation
On line 15, we use the lower helper method from the Str class to convert all the characters of the given strings to their lowercase variants. Using fluent strings is another way of calling the lower helper method on strings. Fluent strings are used on lines 22–23 to lowercase the characters of the given strings.
By utilizing the Str class and its upper and lower methods, we can easily convert strings to uppercase or lowercase within our Laravel application.
Free Resources