Hello everyone,
I am trying to create nice SEO friendly URLs. My company required from me to use yii2 framework and, among others, gave me task that application should have nice SEO friendly URLs with article names displayed in URL, so Google will like it. I wanted to use Sluggable Behaviour, but I got stuck right after I tried what I saw in documentation.
I’ve put this code in my model, and nothing happens:
public function behaviors()
{
return [
[
'class' => SluggableBehavior::className(),
'attribute' => 'title',
// 'slugAttribute' => 'slug',
],
];
}
Then I figure it out that I need to create rules that will use slug, and that I need to pass slug to my view action. I got some advices how to do it, but everything failed.
If I create this rule:
article/<slug>' => 'article/view',
First, I am forced to get articles by title and not by ID, and I need to do it by id. Second, even if I change my code to get articles by slug, my article/index page do not work anymore. Or in some cases, I do not get SEO friendly title in URL ( First-article ), I get "First+article". To make long story short, I made some solution that seem to work, but I am not using Sluggable Behavior at all, or I think I am not. I will show you what I did, and hopefully some one will be able to tell me if my solution is bad, and again hopefully tell be how can I make this work with Sluggable Behavior.
- URLManager rule:
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'article/<id:\d+>/<slug:[-a-zA-Z]+>' => 'article/view',
],
],
- In my index view, I have link that will redirect user to the "view" view, where he can see article:
Url::to(['article/view', 'id' => $model->id, 'slug' => str_replace(' ', '-', $model->title)]) ?>
- My actionView in ArticleController:
public function actionView($id, $slug = null)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
If user clicks on the link on index page, he will get to this URL:
example.com/article/1/First-article
This is it, I am not using Sluggable Behavior at all.
Am I doing this wrong ? And if I do, how can I do this with Sluggable Behavior. Thanks in advance