DEV Community

TRUNG VU
TRUNG VU

Posted on

Create Custom Helper Class in Laravel 7

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

namespace 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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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

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

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"
    ]
},
Enter fullscreen mode Exit fullscreen mode

Run follow command in Terminal:

composer dump-autoload
Enter fullscreen mode Exit fullscreen mode

How to use:

In controller code

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

In blade template

{{ SiteHelper::slug('dolor sit qui amet qui') }}
Enter fullscreen mode Exit fullscreen mode

I hope it can help you.

Top comments (0)