Yii2 replace spaces with dash when using sluggable behaviour

How can I replace spaces with a dash when using sluggable behaviour? As it currently replaces spaces with a plus or percentage symbol.


 public function behaviors()


    return [



            'class' => SluggableBehavior::className(),

            'attribute' => 'title',




My URL manager config

       'urlManager' => [

        'class' => 'yii\web\UrlManager',

        'enablePrettyUrl' => true,

        'showScriptName' => false,

        'rules' => [

            // your rules go here

            'article/<id:\d+>/<slug>' => 'article/view',



Weird, it should and it does replace spaces with dashes. Well, at least my version of Yii…

Have you got any changes made to SluggableBehavior::getValue()? Specially when calling Inflector::slug().

What version are you using?

Also given my above setup how should I be echoing the URL to the view in my index?(as i am outputting it wrong)

The latest one.

As for the url - I guess: Url::to([‘article/view’, ‘id’ => $model->id, ‘slug’ => $model->slug]).

Awesome think I have got it nearly set up properly.

One question how can I prevent duplicates as I can access the post using the real slug for example


but I can also access it if I use the wrong slug as long as I have the id for example


When quering for the model with given id and slug always check both in find() method (not just id) otherwise you risk someone will spread the link with some fake slug that could be offensive (as a joke or to compromise you). Of course this matters only if you care about that risk ;)

All working one more question haha :P

How do should trailing slashes be handled? Using .htaccess?

As currently the url can be accessed

/article/1/test - works

/article/1/test/ - 404 not found error 

Now you can add

'suffix' => '/' //add trailing slash to URL

However then the 404 error occurs when not adding a slash so should I be using a htaccess/server rewrite?

See the discussion about this here: https://github.com/yiisoft/yii2/issues/1807

Just to let you/other know I opted for the following solution (tell me if wrong/if theres a better way)

Adding the following line to my app config within URL manager

'suffix' => '/',

And then the following in my .htaccess

#force trailing slash

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)([^/])$        /$1$2/ [L,R=301]

This is safe approach.

PS. Shouldn’t be escaped? [^\/]

Here’s a good reference


In your config file

    'components' => [

        'urlManager' => [

            'class' => 'yiiwebUrlManager',

            'enablePrettyUrl' => true,

            'showScriptName' => false,


            'rules' => [

                'article/<id:[a-za-z0-9-]+>/<slug:[a-za-z0-9-]+>' => 'article/view',




Then in your controller

public function actionView($id, $slug) {