Seidih
Seidih

Reputation: 1

how to get a value of id from database table in cakephp

CAKEPHP

I have problem to get id value from table

My table is named "users" and have id PK(int),username(txt) name(txt)

I have tried

$this->users->read('users.id)

To get user id but it doesn't work.

I also tried

$this->request->session()->read('users.id')

I wanna to make a condition like

if($this->users->read('users.id'))==1 

because I wanna hide html code from users with other id. I also try use something like that .....read('users.username')=='admin'but they wont work too

As you see a try to use session() to get id but dont work to

my login function is

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {

                $this->Auth->setUser($user);
            return $this->redirect(['controller'=>'Accounts']);
        }
        $this->Flash->error('blalalalala');
    }
}

This is my first project i cakephp to school so guys can you help me? :) im weak in php


Thx for tips but still dont work.

i use this

$id  =  $this->Auth->user('id');  // To get user id 
    $this->set('id', $id);

in my AppController in funciton before filter.

and i use for example if($id==1) ..... and still dont work. var dump shows null.

i forgot to say but i have CakePHP 3x version

Upvotes: 0

Views: 963

Answers (2)

Alimon Karim
Alimon Karim

Reputation: 4469

To set user any information in controller you can use

$this->Auth->user('fieldName');

In AppController in beforeFilter method just set user info which you need, like as below code

$id  =  $this->Auth->user('id');  // To get user id 
        $this->set('id', $id);   

Now in any view you can apply condition like

if($id==1) 
--do this-- 

If you want to get user id anywhere you can use, It not allow in cakephp 3.x

AuthComponent::user('id')

For details you can see doc

Upvotes: 1

Faiyaz Alam
Faiyaz Alam

Reputation: 1217

you can try these:

 $this->Auth->user('id'); // for controller action

OR

$this->Session->read('Auth.User.id'); // for controller and views

OR

AuthComponent::user('id') // anywhere 

Upvotes: 0

Related Questions