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.)
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.
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.
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.
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...
I think you can do $uid = $this->Auth->user('id');
- check the api: http://api.cakephp.org/class/auth-component#method-AuthComponentuser
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With