Laravel 10 Check If String Starts with Specific Value Example

Hello Artisan, today I'll show you how to check if string starts with specific character in laravel in our Laravel application.  I'd like to demonstrate the usage of the Laravel Str::startsWith method with a simple example. The Str::startsWith() method in Laravel is used to check if a string starts with a specified value. The Str::startsWith() method, when given a string to search and a value to check for at the beginning, returns true if the string commences with the provided value(s); otherwise, it returns false.

let's see the simple example:

Table of Contents

  1. Install Laravel App
  2. Laravel String Starts With in Controller
  3. Output
  4. Laravel String Starts With in Blade File
  5. Output

Install Laravel App

Creating the Laravel app is not necessary for this step, but if you haven't done it yet, you can proceed by executing the following command.

composer create-project laravel/laravel-check

Laravel String Starts With in Controller

We can use it with controller like this way:

app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $string = "Hello, Hardik";
        $result = Str::startsWith($string, 'Hello');

        dd($result);
    }
}

When you visit the URL or route associated with the index method of this controller in your Laravel application, it will execute this code. If the string $string starts with 'Hello', it will display true, otherwise, it will display false.
 

Output

true // app\Http\Controllers\UserController.php:20

Laravel String Starts With in Blade File

You can use it with blade file like this way:

Blade File Code:

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

Output:

false

That's it for today. I hope it'll be helpful in upcoming project. You can also download this source code from GitHub. Thanks for reading. ๐Ÿ™‚