DevBlog

Coding my way

9 months ago in PHP, Laravel · 1 MIN READ

Fixing slug generation problems

I was recently building a small company's website, and ran into a problem with Laravel's slug generation problem that affects non-Germanic languages, like Hungarian and Turkish.

In this case, Laravel's str_slug() did the following transformations:

ö => oe
ü => ue

While this is good, for Germanic languages, other types use a much simpler conversion:

ö => o
ü => u

As we went deeper into the rabbit hole (that's laravel's source for you), some nasty things surfaced. A brief history can be read at https://github.com/laravel/framework/issues/16622, but the ticket got quickly shot down...

You just got Campbelled by Hocza

Long story short, until this is resolved one way or another... A really obscure but powerful tool can be a temporary solution for this. It's called Helper Overloading. Laravel's helpers are created in a way that checks if the method already exists, for example:

if (! function_exists('str_slug')) {
    /**
     * Generate a URL friendly "slug" from a given string.
     *
     * @param  string  $title
     * @param  string  $separator
     * @return string
     */
    function str_slug($title, $separator = '-')
    {
        return Str::slug($title, $separator);
    }
}

This is really great, the only thing remaining is to actually add our own method before Laravel creates it own version. Thankfully there's an easy way to do that!

First, we'll need to create our function. A recommendation would be to create this file at app\Helpers\HelperOverload.php with the following contents:

if (! function_exists('str_slug')) {
    /**
     * Generate a URL friendly "slug" from a given string.
     *
     * @param  string  $title
     * @param  string  $separator
     * @return string
     */
    function str_slug($title, $separator = '-')
    {
        return (string) \Stringy\Stringy::create($title)->slugify($separator,'hu');
    }
}

The next step would be actually load this file before Laravel's, We can do this in the bootstrap\autoload.php file:

require __DIR__.'/../app/Helpers/HelperOverload.php'; // just add this before the autoload.php file
require __DIR__.'/../vendor/autoload.php';

You can freely create new or overload existing helpers to fully customize your Laravel application.

···

Miklós Galicz

I'm a hobbyist who managed to become a professional web developer who specializes in Laravel and Vue.js, also the Spice must flow.
comments powered by Disqus


© 2017 DevBlog