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:
- Install Laravel App
- Laravel String Starts With in Controller
- Output
- Laravel String Starts With in Blade File
- Output
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
We can use it with controller like this way:
<?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.
true // app\Http\Controllers\UserController.php:20
You can use it with blade file like this way:
<p>{{ Str::startsWith("Hello, Hardik", 'hello') }}</p>
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. ๐