Search

Laravel String Helper Function: ucfirst

November 16, 2016 —John Koster

The ucfirst helper method is used to uppercase the first letter of a string. It defines only one parameter—$string—which is the string that should have its first letter upper cased. This helper method differs from PHP's ucfirst function because the Laravel helper method handles multi-byte strings by reimplementing the ucfirst function using PHP's multibyte string API.

The signature for the ucfirst helper function is:

ucfirst($string)

The following example demonstrates the usage of the ucfirst helper method:

1use Illuminate\Support\Str;
2 
3// A simple string to work with.
4$testString = 'this is a sentence.';
5 
6// This is a sentence.
7$upper cased = Str::ucfirst($testString);

The ucfirst helper method can be quite useful when combined with the finish helper method. For example, we can combine these two methods to ensure the that a sentence starts with an upper cased letter and ends with a period (or full stop):

1use Illuminate\Support\Str;
2 
3// This is a sentence.
4$firstValue = Str::finish(Str::ucfirst('this is a sentence'), '.');
5 
6// This is a sentence.
7$secondValue = Str::finish(Str::ucfirst('this is a sentence.'), '.');

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.