droc60607 2018-01-22 05:21
浏览 49
已采纳

如何在url中添加用户名而不是cakephp 3中的user_id

I want my url like this format http://localhost/blog/users/username instead of this http://localhost/blog/users/view/6

I have this code in Users view index.ctp

enter image description here

<?php foreach ($users as $user): ?>
<?= $this->Html->link(__('View Profile'), ['action' => 'view', $user['user']['slug']]) ?>
<?php endforeach; ?>

routes.php

<?php
 $routes->connect('/user/*', array('controller' => 'users', 'action' => 'view'));
?>


//public function view($id = null)
public function view($username)
{

    $users = $this->Users->get($username, [
        'contain' => ['Subjects'] // i have relation
    ]);
    $this->set('users', $users);
    $this->set('_serialize', ['user']);
}

I tried this link but it not solved my problem

public function edit($id = null)
{
  //$logged_user_id=$this->request->Session()->read('Auth.user.id');


  $logged_user_id=$this->Auth->user('id');
  if($logged_user_id==$id){
      $user = $this->Users->get($id, [
        'contain' => []
    ]);
      if ($this->request->is(['patch', 'post', 'put'])) {
        $user = $this->Users->patchEntity($user, $this->request->getData());


        if ($this->Users->save($user)) {
            $this->Flash->success(__('User profile successfuly  updated.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }

    }
    $this->set(compact('user'));
    $this->set('_serialize', ['user']);
} else {
    $this->Flash->error(__('You are not allowed to do this.'));
    return $this->redirect(['action' => 'index']);
}

}

  • 写回答

2条回答 默认 最新

  • doushan1850 2018-01-22 09:07
    关注

    In index.ctp

    <?php foreach ($users as $user): ?>
    <?= $this->Html->link(__('View Profile'), ['action' => 'view', $user->username]) ?>
    <?php endforeach; ?>
    

    Please change $user->username as per your structure.

    You don't have to do anything in your routs.php

    the username will receive as an argument of the function view

    function view($username){
        //Your code
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同