How to updateOwnPost on function UPDATE in PostController.php

According to the [color="#0000FF"]guide-security-authorization[/color], admin can edit all post, and user can edit his own post. But the GUIDE did not gave an function update example of postController.php.

I am using yii2-app-advanced template.

In postController.php, there is a function named actionUpdate. I have modified it like this, but only the post owner can edit his post, admin can not edit any post.

    public function actionUpdate($id)


        $model = $this->findModel($id);

        if (\Yii::$app->user->can('updateOwnPost', array('post' => $model)) ) {

            if ($model->load(Yii::$app->request->post()) && $model->save()) {

                return $this->redirect(['view', 'id' => $model->id]);

            } else {

                return $this->render('update', [

                    'model' => $model,




        else {

            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));



Someone could give an example?

You shouldn’t check for permissions like “updateOwnPost” directly. Use “->can(‘updatePost’)”, and the RBAC manager will automatically check if it the current user can reach that permission through another one (such as updateOwnPost).

Like tvdavid said, you don’t need to check ‘updateOwnPost’ directly.

An easy way to understand RBAC is to think of it as multiple roads.

You start from point A (the permission you are checking) and you try to get to B (the user).

So in this example, you are John and you want to update a post (updatePost) which happens to be one of your post.

  • RBAC check if updatePost is assigned to your role directly (it isn’t)

  • It then check if there is another ‘road’ to your user. (there is)

  • It finds another ‘road’ through ‘updateOwnPost’, but there is a rule attached to it that needs to be matched (if the user_id and user id match, you can pass)

  • It then checks if you have the author role (you do)

  • A ‘road’ has been found, which mean you can ‘updatePost’ for that specific post.

If we take the same example and pretend that you are Jane, trying to update the same post (John’s post), it’s more simple.

  • RBAC check if updatePost is assigned to your role directly (it is)

  • A ‘road’ has been found, no need to check if user_id is the same as user id

Thank tvdavid and Alain L.