Yii2 display model name in URL

Now my view url is looking like this example.com/item/view?id=1, i need it too look like this: example.com/item/item-name. As I understood, I need to use SluggableBehavior. But how do I configure my URLManager rules and SluggableBehavior to access this?

Upvotes: 0

Views: 87

Answers (1)

rob006
rob006

Reputation: 22174

You need to configure rules in UrlManager:

[
    'components' => [
        'urlManager' => [
            // ...
            'rules' => [
                'item/<slug:[\w\-]+>' => 'item/view',
                // ...
            ],
        ],
    ],
]

Then you create URL like this:

Url::to(['item/view', 'slug' => $model->slug]);

And in action:

public function actionView($slug) {
    $model = Item::findOne(['slug' => $slug]);
    // rest of action logic
}

It is worth to take look at handling pretty URLs documentation.

Configuring SluggableBehavior is quite well documented:

public function behaviors()
{
    return [
        [
            'class' => SluggableBehavior::className(),
            'attribute' => 'title',
            // 'slugAttribute' => 'slug',
        ],
    ];
}

Upvotes: 1

Related Questions