Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp - get user id in controller when using Auth

Tags:

cakephp

It seems like a two-step process to get this,

    $u = $this->Auth->user();
    $uid = $u['User']['id'];

Isn't there a variable set somewhere once a user is logged in? (Sorry for the dumb question.)

like image 295
Owen Avatar asked Jul 01 '10 15:07

Owen


People also ask

How do I find my user ID in Auth?

The answer: using the Auth facade. When Laravel is configured with authentication, the Auth facade becomes useful for actions like grabbing the current logged in user id. Auth comes with various methods, one of which is the id() method, and this is where we can grab the authenticated users' information.

How does CakePHP manage users and user authorization?

In CakePHP this is handled by the AuthComponent , a class responsible for requiring login for certain actions, handling user sign-in and sign-out, and also authorizing logged in users to the actions they are allowed to reach. To add this component to your application open your app/Controller/AppController.

What is CakePHP Auth?

In CakePHP, there are several built-in ways of authenticating users stored in your application. FormAuthenticate allows you to authenticate users based on form POST data. Usually, this is a login form that users enter information into. BasicAuthenticate allows you to authenticate users using Basic HTTP authentication.


2 Answers

In CakePHP there are several ways to get the user id from the session, here are a few examples

To get the session user id within the controller use:

$uid = $this->Auth->User('user_id');

To get the session user id within a view, use: ( Not Recommended, I would set this in the controller)

$uid = $this->Session->read('Auth.User.id');

To get the session user id within a model, use: (Not Recommended, but a solution)

$uid = CakeSession::read('Auth.User.id');

I don't recommend the above to get the session user id from within the model, I would pass it via the controller, use:

$this->Model->function($uid);

You can also get the session user id via pure php, use: (Althought using Cake you should stick with the conventions)

$uid = $_SESSION['Auth']['User']['id'];

And there are more approaches, this is just a few...

like image 40
Brett Stewart Avatar answered Sep 19 '22 18:09

Brett Stewart


I think you can do $uid = $this->Auth->user('id'); - check the api: http://api.cakephp.org/class/auth-component#method-AuthComponentuser

like image 88
Leo Avatar answered Sep 20 '22 18:09

Leo