質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

CakePHP

CakePHPは、PHPで書かれたWebアプリケーション開発用のフレームワークです。 Ruby on Railsの考え方を多く取り入れており、Railsの高速性とPHPの機動性を兼ね備えています。 MVCやORMなどを「規約優先の考え方」で利用するため、コードを書く手間を省くことができます。 外部のライブラリに依存しないので、単体での利用が可能です。

Q&A

1回答

1326閲覧

CakePHP2.xでログインしたユーザの情報にアクセスしたい

halucondo

総合スコア0

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

CakePHP

CakePHPは、PHPで書かれたWebアプリケーション開発用のフレームワークです。 Ruby on Railsの考え方を多く取り入れており、Railsの高速性とPHPの機動性を兼ね備えています。 MVCやORMなどを「規約優先の考え方」で利用するため、コードを書く手間を省くことができます。 外部のライブラリに依存しないので、単体での利用が可能です。

0グッド

0クリップ

投稿2021/11/14 10:14

編集2021/11/15 05:06

CakePHP2.xでログインしたユーザの情報にアクセスしたい

PHP(CakePHP2.xで簡単な掲示板を作っています。
公式のシンプルな認証と承認のアプリケーションで紹介されているコードを参考にしてコードを書いています。

新規投稿をした時、今ログインしているユーザのID(=投稿者のID)を一緒に登録させたいですが
うまく登録することができません。

発生している問題・エラーメッセージ

ログインしているユーザの情報にアクセスをし、
新規投稿をするときに、一緒にuser_idも登録させたいです。

しかし、この方法を参考に
$this->request->data['Post']['user_id'] = $this->Auth->user('id');
とすると、user_idはNULLとして登録をされてしまいます。

該当のソースコード

View/Users/login.ctp

<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <h1>Login</h1> <div class="users form"> <?php echo $this->Flash->render('auth'); ?> <?php echo $this->Form->create('User'); ?> <?php echo __('登録したメールアドレスとパスワードを入力してください。'); ?> <?php echo $this->Form->input('email'); echo $this->Form->input('password'); ?> <?php echo $this->Form->end(__('ログイン')); ?> </div> </body> </html>

Controller/UsersController.php

<?php App::uses('AppController', 'Controller'); class UsersController extends AppController { public $helpers = array('Html', 'Form', 'Flash'); public $components = array('Flash'); public function beforeFilter() { //未ログイン者が見れるページ parent::beforeFilter(); $this->Auth->allow('add', 'logout'); } public function add() { //ログイン済の場合 if ($this->Auth->loggedIn()) { return $this->redirect(array('controller' => 'posts', 'action' => 'index')); } if ($this->request->is('post')) { $this->User->create(); if ($this->User->save($this->request->data)) { $this->Flash->success(__('会員登録が完了しました。')); return $this->redirect(array('action' => 'login')); } $this->Flash->error(__('登録に失敗しました。再度お試しください')); } } public function login() { //ログイン済の場合 if ($this->Auth->loggedIn()) { return $this->redirect(array('controller' => 'posts', 'action' => 'index')); } //POSTデータが送られてきた時 if ($this->request->is('post')) { //ログインを行う if ($this->Auth->login()) { $this->Flash->success(__('ログインできました。')); //ログインが成功ならユーザーが最後に訪れていたページへリダイレクト return $this->redirect($this->Auth->redirectUrl()); } else { //ログインが失敗ならフラッシュメッセージがセットされる $this->Flash->error(__('ログインに失敗しました。')); } $this->Flash->error(__('メールアドレスもしくはパスワードが違います。')); } } public function logout() { if ($this->Auth->login()) { $this->Flash->success(__('ログアウトしました。')); $this->redirect($this->Auth->logout(array('controller' => 'posts', 'actoin' => 'index'))); } $this->redirect($this->Auth->redirect(array('controller' => 'posts', 'action' => 'index'))); } public function view($id = null) { if (!$id) { throw new NotFoundException(__('無効な操作です。')); } $user = $this->User->findById($id); if (!$user) { throw new NotFoundException(__('無効な操作です。')); } $this->set('user', $user); } } ?>

Controller/PostsController.php

<?php class PostsController extends AppController { public $helpers = array('Html', 'Form', 'Flash'); public $components = array('Flash'); public function index() { $user = $this->Auth->user(); $this->set('user', $user); $this->set('posts', $this->Post->find('all')); } public function view($id = null) { if (!$id) { throw new NotFoundException(__('無効な操作です。')); } $post = $this->Post->findById($id); if (!$post) { throw new NotFoundException(__('無効な操作です。')); } $this->set('post', $post); } public function isAuthorized($user) { if ($this->action === 'add') { return true; } if (in_array($this->action, array('edit', 'delete'))) { $postId = (int) $this->request->params['pass'][0]; if ($this->Post->isOwnedBy($postId, $user['id'])) { return true; } else { $this->Flash->error(__('削除された投稿、自分以外の投稿は編集・削除ができません。')); return $this->redirect(array('action' => 'index')); } } return parent::isAuthorized($user); } //Add post public function add() { if ($this->request->is('post')) { $this->request->data['Post']['user_id'] = $this->Auth->user('id'); //データがあれば保存する if ($this->Post->save($this->request->data)) { $this->Flash->success(__('投稿されました。')); return $this->redirect(array('action' => 'index')); } } } public function edit($id = null) { if (!$id) { throw new NotFoundException(__('無効な操作です。')); } $post = $this->Post->findById($id); if (!$post) { throw new NotFoundException(__('無効な操作です。')); } if ($this->request->is(array('post', 'put'))) { $this->Post->id = $id; if ($this->Post->save($this->request->data)) { $this->Flash->success(__('編集できました。')); return $this->redirect(array('action' => 'index')); } $this->Flash->error(__('編集できません。再度お試しください。')); } if (!$this->request->data) { $this->request->data = $post; } } public function delete($id) { if ($this->request->is('get')) { throw new MethodNotAllowedException(); } if ($this->Post->delete($id)) { $this->Flash->success(__('id: %s の投稿を削除しました。', h($id))); } else { $this->Flash->error(__('id: %s の投稿は削除できませんでした。', h($id))); } return $this->redirect(array('action' => 'index')); } } ?>

試したこと

$this->request->data['Post']['user_id'] = $this->Auth->user('id');
では登録ができませんが、
$user = $this->Auth->user('id');
$this->request->data['Post']['user_id'] = $user['id'];
とすると、user_idを登録することができます。

CakePHP $this->Auth->user('フィールド')が取得できない時にチェックすべきこと
というサイトを参考に、
ログイン時に渡す引数を間違えているのではないかと思い
View/Users/login.ctp
Controller/UsersController.php
などを見直しました。
しかし、ログイン時は
$this->Auth->login()
に引数は設定していませんので、階層がおかしくなることはないのではないかと考えています。

補足情報

CakePHP2.xを使って作っています。

何が原因で
$this->request->data['Post']['user_id'] = $this->Auth->user('id');
これでuser_idが代入できないのか、
どうしたら代入できるようになるのか教えていただきたいです。

「試したこと」で記載した方法では、自体は可能ですが
ID取得を他の機能でも使いたいため、行数が多くなってしまうのを避けたいです。

何卒ご教授のほど、よろしくお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

m.ts10806

2021/11/14 11:56

>$this->Auth->user('id') では取得することができませんが どのように確認しているのでしょう。
halucondo

2021/11/15 04:26

ご指摘ありがとうございます。 表現を間違えました。 正しくは Controllerの中でログインしたユーザの情報にアクセスをしたい ということです。 質問内容も修正いたします。
guest

回答1

0

$this->request->data['Post']['user_id'] = $this->Auth->user('id');

では登録ができませんが、
$user = $this->Auth->user('id');
$this->request->data['Post']['user_id'] = $user['id'];
とすると、user_idを登録することができます。

上記の件を踏まえると
$this->Auth->user('id')をpr()してもらうと、おそらく

php

1Array 2( 3 [id] => Array 4 ( 5 [id] => 10 6 [password] => ???????????????????????????? 7 [email] => test@example.com 8 ) 9) 10

こんな感じで出るんではないでしょうか。

原因としてはログイン処理にあるか、Authの処理(こっちが怪しい)ので今一度ご確認してみてください
またpr()で値を出力すると気付くこともあるので出力することをおすすめします。

投稿2021/12/06 10:00

Nash-BETA

総合スコア233

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問