Laravel 10 Check If String Starts with Specific Value Example

Laravel 10 Check If String Starts with Specific Value Example

 Laravel 10 Check If String Starts with Specific Value Example

Hello Artisan, today I'll show you how to check if the string starts with a 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 a simple example:

Table of Contents

  1. Install Laravel App
  2. Laravel String Starts Within Controller
  3. Output
  4. Laravel String Starts Within 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 Within Controller

We can use it with a controller 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 Within Blade File

You can use it with a blade file 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 an upcoming project. Thanks for reading. 🙂

Reactions

Post a Comment

0 Comments

close