Create Custom Helper Class in Laravel 7

Trung Vu
2 min readMay 10, 2021

In this article, let’s learn how to create a custom helper class in Laravel 7.

First step, create a app\Utilities folder.

Next, create a app\Utilities\SiteHelper.php file.

Then add following code into that file

<?phpnamespace App\Utilities;class SiteHelper
{
public static function slug(string $str): string
{
$str = self::stripVnUnicode($str);
$str = preg_replace('/[^A-Za-z0-9-]/', ' ', $str);
$str = preg_replace('/ +/', ' ', $str);
$str = trim($str);
$str = str_replace(' ', '-', $str);
$str = preg_replace('/-+/', '-', $str);
$str= preg_replace("/-$/", '', $str);
return strtolower($str);
}
public static function stripVnUnicode(string $str): string
{
if (!$str) {
return false;
}
$str = strip_tags($str);
$unicode = [
'a' => 'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ',
'd' => 'đ',
'e' => 'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ',
'i' => 'í|ì|ỉ|ĩ|ị',
'o' => 'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ',
'u' => 'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự',
'y' => 'ý|ỳ|ỷ|ỹ|ỵ',
'A' => 'Á|À|Ả|Ã|Ạ|Ă|Ắ|Ặ|Ằ|Ẳ|Ẵ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ',
'D' => 'Đ',
'E' => 'É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ',
'I' => 'Í|Ì|Ỉ|Ĩ|Ị',
'O' => 'Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ',
'U' => 'Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự',
'Y' => 'Ý|Ỳ|Ỷ|Ỹ|Ỵ',
];
foreach($unicode as $key => $value) {
$str = preg_replace("/($value)/i", $key, $str);
}
return $str;
}
}

In config\app.php, add key and value in array of Aliases.

return [
//...
'aliases' => [
//...
'SiteHelper' => App\Utilities\SiteHelper::class,
],
];

And then in your composer.json file add the following “files” array to the autoload section. It should look something like this:

"autoload": {
// ...
"files": [
"app/Utilities/SiteHelper.php"
]
},

Run follow command in Terminal:

composer dump-autoload

How to use:

In controller code

use SiteHelper;public function test()
{
dd(SiteHelper::slug('dolor sit qui amet qui'));
}

In blade template

{{ SiteHelper::slug('dolor sit qui amet qui') }}

I hope it can help you.

--

--