Laravel 10 Check If String Starts with Specific Value Example

Laravel 10 Check If String Starts with Specific Value Example

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

  1. Install Laravel App

  2. Using Str::startsWith() in a Controller

  3. Output (Controller)

  4. Using Str::startsWith() in a Blade File

  5. Output (Blade)

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:

composer create-project laravel/laravel laravel-check

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

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Str; class UserController extends Controller { public function index(Request $request) { $string = "Hello, Hardik"; $result = Str::startsWith($string, 'Hello'); dd($result); // Outputs: true } }

Output (Controller) <a name="output-controller"></a>

true

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:

<p>{{ Str::startsWith('Hello, Hardik', 'hello') }}</p>

šŸ”¹ Note: The method is case-sensitive. 'Hello''hello'.

Output (Blade) <a name="output-blade"></a>

false

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!

Souy Soeng

Souy Soeng

Hi there šŸ‘‹, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
šŸ‘Æ I’m looking to collaborate on open-source PHP & JavaScript projects
šŸ’¬ Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close