Search code examples
laravellaravel-9sluglaravel-helper

Keep original string language in laravel slug


With laravel(I am using v.9.x) Str:slug you can convert a string to a slug like:

Woman life freedom

to

Woman-life-freedom

but the problem is when you pass a non-english string to this method, laravel translates it to English like in persian:

زن زندگی آزادی

it converts to:

zn-zndgy-azady

How to prevent laravel to do this?


Solution

  • The simple solution to this problem is to pass null or 0 as the third argument to the method slug like this:

    Str:slug('String', '-', null);
    

    Why?

    if you look at the source code of the slug method in the Str class at /vendor/laravel/framework/src/Illuminate/Support/Str.php, you can see this:

    public static function slug($title, $separator = '-', $language = 'en', $dictionary = ['@' => 'at'])
    {
        $title = $language ? static::ascii($title, $language) : $title;
    

    It is clear that the third parameter $language allows you to translate the language if it is specified, else it will use English as the default.

    So by passing the value 0 (or null, that is better), the condition is not executed and the text remains in its original form.