kkhicher1
2 weeks ago

Slug for Hindi Words

Posted 2 weeks ago by kkhicher1

I working on a website that is on laravel. I getting issue when admin add a hindi word.

Word - कोरोनावायरस URL - https://wordkosh.com/hindi-english/करनवयरस-meaning-english

Hindi Slug Code -

<?php

namespace App\Functions;

class Slug
{
    /**
     * @param $title
     * @param $model = App\Category, App\Post, App\User .............
     * @param int $id
     * @return string
     * @throws \Exception
     */
    public static function createSlug($title, $model, $id = 0)
    {
        // Normalize the title
        $slug = str_slug($title);
        // Get any that could possibly be related.
        // This cuts the queries down by doing it once.
        $allSlugs = self::getRelatedSlugs($slug, $model, $id);
        // If we haven't used it before then we are all good.
        if (!$allSlugs->contains('slug', $slug)) {
            return $slug;
        }
        // Just append numbers like a savage until we find not used.
        for ($i = 1; $i <= 50; $i++) {
            $sufix = \substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 4);
            $newSlug = $slug . '-' . $sufix;
            if (!$allSlugs->contains('slug', $newSlug)) {
                return $newSlug;
            }
        }
        throw new \Exception('Can not create a unique slug');
    }

    public static function makeHindiSlug($string, $separator = '-')
    {
        if (is_null($string)) {
            return "";
        }

        // Remove spaces from the beginning and from the end of the string
        $string = trim($string);

        // Lower case everything 
        // using mb_strtolower() function is important for non-Latin UTF-8 string | more info: http://goo.gl/QL2tzK
        $string = mb_strtolower($string, "UTF-8");;

        // Make alphanumeric (removes all other characters)
        // this makes the string safe especially when used as a part of a URL
        // this keeps latin characters and arabic charactrs as well
        $string = preg_replace("/[^a-z0-9_\s-अआइईउऊएऐओऔअंअःऋॠऌॡकखगघङचछजझञटठडढणड़ढ़तथदधनपफबभमयरलवशषसहक्षत्रज्ञ]/u", "", $string);

        // Remove multiple dashes or whitespaces
        $string = preg_replace("/[\s-]+/", " ", $string);

        // Convert whitespaces and underscore to the given separator
        $string = preg_replace("/[\s_]/", $separator, $string);

        return $string;
    }



    protected static function getRelatedSlugs($slug, $model, $id = 0)
    {
        return $model::select('slug')->where('slug', 'like', $slug . '%')
            ->where('id', '<>', $id)
            ->get();
    }
}

Please sign in or create an account to participate in this conversation.