How to Check if a String Starts with a Specific Value in Laravel
Hello Artisan!
In today’s guide, we’ll explore how to determine whether a string starts with a specific character or word using Laravel’s built-in Str::startsWith()
helper method. This method is part of Laravel's powerful Illuminate\Support\Str
class and provides a clean way to perform string inspections.
What is Str::startsWith()
?
The Str::startsWith()
method checks whether a given string begins with one or more specified substrings.
It returns:
-
true
if the string starts with the specified value. -
false
otherwise.
Table of Contents
Install Laravel App <a name="install-laravel-app"></a>
If you haven’t set up a Laravel application yet, you can create one using the following command:
Using Str::startsWith()
in a Controller <a name="in-controller"></a>
Here's how to use it inside a controller:
File: app/Http/Controllers/UserController.php
Output (Controller) <a name="output-controller"></a>
The output confirms that the string starts with "Hello".
Using Str::startsWith()
in a Blade File <a name="in-blade"></a>
You can also use this helper method directly in a Blade view.
Example Blade Code:
š¹ Note: The method is case-sensitive.
'Hello'
≠'hello'
.
Output (Blade) <a name="output-blade"></a>
Conclusion
And that’s it! You’ve now learned how to use the Str::startsWith()
method in both controllers and Blade files. It's a simple yet powerful utility for string validation in Laravel.
Thanks for reading — happy coding!