I
I
Iossarian2019-03-04 17:46:38
Yii
Iossarian, 2019-03-04 17:46:38

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

3 answer(s)
M
Maxim Timofeev, 2019-03-04
@Iossarian

Put a lib, which in the database in the slug field generates it from the title of the news

For this, there is a behavior out of the box, no additional ones are needed:
https://www.yiiframework.com/doc/api/2.0/yii-behav...
Just connect it in the model and specify what to transliterate and where.
You found a model in the action, but then look for it again, what's the point?
public function actionView($slug)
    {
      $model = News::find()->where(['slug' => $slug])->one(); //вот тут вы уже нашли модель по slug
  
        return $this->render('view', [
            'model' => $this->findModel($slug), //вот тут вместо того что бы передать найденную модель, дергаете функцию findModel непонятно зачем
        ]);
    }

Somehow it must be
public function actionView($slug)
    {
       if($model = News::find()->where(['slug' => $slug])->one()){
           return $this->render('view', [
               'model' => $model
           ]);
       }
       throw new NotFoundHttpException('Не найдено такой новости,  может под стол закатилась, мы поищем завтра.');
    }

in url manager something like
'rules' => [
                '/' => 'site/index',
                '/news/<slug>/' => 'news/view',
            ],

P
padlyuck, 2019-03-04
@padlyuck

Search on the toaster

I
ivanitch, 2019-10-31
@amurcoder

There are several ways.
The easiest way to make a slug in Yii2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question