Create a slug field in your db.
Tell it to load by slug not the id in your controller.
some people like yoursite.com/1/some-title that way you don’t get hit on search engines for “broken” pages when someone changes the tile/slug attribute.
i.e.
yoursite.com/about
then someone changes your about page to about us
yoursite.com/about-us
now search engines have your about page indexed as about instead of about-us. Thus throwing a 404 page and lowering your rankings.
You can make it so the slug cant ever be changed so you don’t have to be worried about rankings.
Use the method that leave an id / slug.
Or just let it be and not worry about rankings.
//slug is not required to load page. this method is used for site.com/1/some-slug
public function actionView($id, $slug = NULL) {
$model = $this->findModel($id);
}
protected function findModel($id) {
if (($model =Post::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
or
public function actionView($slug) {
$model = $this->findModel($slug);
}
protected function findModel($slug) {
if (($model =Post::findOne($slug)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
make sure you are calling your urls correctly too .i.e
<?= Html::a($model->title,['post/view','id'=>$model->id, 'slug'=>$model->slug]);
or
<?= Html::a($model->title,['post/view', 'slug'=>$model->slug]);
call it normally and let the urlmanager correct them. that way if you ever change your rule you don’t have to change all of your buttons, links etc.
Use a behavior or function in your model to save the slugs into your db.
i.e.
Yii2’s built in sluggable behavior
Use a rewrite rule for the slug not Id. Also, you want the slugs to be called dynamically not statically or you will have to create a rule for every single page.
'post/<id:\d+>/<slug>' => 'post/view',
or
'post/<slug>' => 'post/view',