Answer the question
In order to leave comments, you need to log in
How to implement slug in yii2?
Good evening. My task is the following - to replace scary urls with slugs on the yii2 project. I put a lib that in the database in the slug field generates it from the news title, it remains to put these slugs in the url itself. Tell me how to implement it correctly?
public function actionView($slug)
{
$model = News::find()->where(['slug' => $slug])->one();
return $this->render('view', [
'model' => $this->findModel($slug),
]);
}
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'' => 'site/index',
'<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
],
],
Answer the question
In order to leave comments, you need to log in
Put a lib, which in the database in the slug field generates it from the title of the news
public function actionView($slug)
{
$model = News::find()->where(['slug' => $slug])->one(); //вот тут вы уже нашли модель по slug
return $this->render('view', [
'model' => $this->findModel($slug), //вот тут вместо того что бы передать найденную модель, дергаете функцию findModel непонятно зачем
]);
}
public function actionView($slug)
{
if($model = News::find()->where(['slug' => $slug])->one()){
return $this->render('view', [
'model' => $model
]);
}
throw new NotFoundHttpException('Не найдено такой новости, может под стол закатилась, мы поищем завтра.');
}
'rules' => [
'/' => 'site/index',
'/news/<slug>/' => 'news/view',
],
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question