Laravel String Contains Case Insensitive Example

By Hardik Savani April 16, 2024 Category : Laravel

Hey Folks,

This example is focused on laravel string contains case insensitive. We will look at an example of string contains case insensitive laravel. you can see string contains case insensitive in laravel. This tutorial will give you a simple example of laravel str macro contains case insensitive.

Laravel Str helper provides contains() to check word is contain on given string. But it's checked in case sensitive. If you need to check with case insensitive then we need to create our own Str help in laravel. so we will create containsInSensitive() and use it. So, let's see the simple code:

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Step 1: Create containsInSensitive() Helper

We need to define containsInSensitive() helper in AppServiceProvider.php file. let's update provide file.:

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Contracts\Foundation\Application;

use Illuminate\Filesystem\FilesystemAdapter;

use Illuminate\Support\Facades\Storage;

use League\Flysystem\Filesystem;

use Illuminate\Support\Str;

class AppServiceProvider extends ServiceProvider

{

/**

* Register any application services.

*/

public function register(): void

{

}

/**

* Bootstrap any application services.

*/

public function boot(): void

{

Str::macro('containsInSensitive', function($haystack, $needles)

{

foreach ((array) $needles as $needle) {

if ($needle !== '' && mb_stripos($haystack, $needle) !== false) {

return true;

}

}

return false;

});

}

}

Step 2: Use containsInSensitive() Helper

Here, we will use containsInSensitive() helper function and check the result. so, let's update controller method:

app/Providers/AppServiceProvider.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)

{

$result = Str::containsInSensitive('Hi, He is Hardik', 'Hardik');

$result2 = Str::containsInSensitive('Hi, He is Hardik', 'hardik');

dd($result, $result2);

}

}

Output:

true

false

I hope it can help you...

Tags :
Shares