LoginSignup
11
11

More than 5 years have passed since last update.

CakePHP $this->Auth->user('フィールド')が取得できない時にチェックすべきこと

Last updated at Posted at 2013-06-21

要約

$this->Auth->login() に渡す引数は、配列の階層に注意!

現象

ExamplesController.php
          
    $id = $this->Auth->usesr('id');
          

上記のコードでログイン中のユーザのIDを取得できていた。
が、別な場所をいじっていたら突然、上記のコードで ID が取得できたりできなかったりするようになった。
全く同じ行を通っているのに。

別な現象

調査中に、下のコードで2通りの出力が得られた。

ExamplesController.php
          
    $auth = $this->Auth->user();
    pr($auth);
          

それぞれ↓

結果1
Array
(
    [id] => 10
    [username] => tengu
    [password] => ????????????????????????????
    [status] => 0
    [created] => 2013-06-20 17:06:55
    [modified] => 2013-06-20 17:06:55
)
結果2
Array
(
    [User] => Array
    (
        [id] => 10
        [username] => tengu
        [password] => ????????????????????????????
        [status] => 0
        [created] => 2013-06-20 17:06:55
        [modified] => 2013-06-20 17:06:55
    )
)

つまり、戻り値の配列の階層が違っているのだ。
結果1が得られる場合は、$this->Auth->user('id') でIDを取得できるが、結果2が得られる時はIDが取得できなかった。

原因

ログインする部分が2通りあり、それぞれに渡す引数の配列の階層が違っていたようだ。

値取得がうまくいくログイン
      // 引数なし(ビューのフォームの値でログインする)
      $this->Auth->login();

      // または配列の第一階層に各フィールドが来るような引数
      $user = $this->User->findById(10); // ID=10のユーザでログイン
      $this->Auth->login($user['User']);
値取得がうまくいかないログイン
      // 配列の第二階層に各フィールドが来るような引数
      $user = $this->User->findById(10); // ID=10のユーザでログイン
      $this->Auth->login($user);

Auth:login() は、とにかく渡した引数で認証したことにしてしまうので、階層や値は呼び出し側できちんと考えてやらないと。

11
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11