Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current user from View

So what I want to do is, in my main layout, have a menu for logged in users, and a different for anon users.

THe layout will be used on every page, so I'm not sure how to do this, as I've seen, the Auth Component can only be used in the controller, this would be nice if I had to do this in only one view, but for every view, how can I do this? Do I have to do something on AppController?

What I want to do is basically

// layout
<?php if(logged): ?>
Welcome <?php echo $user; ?>
<?php else: ?>
Welcom anon, Log in?
<?php endif; ?>
like image 279
gosukiwi Avatar asked Sep 16 '12 02:09

gosukiwi


1 Answers

You can access the logged in user in your view using the Auth component as well. From the manual:

Once a user is logged in, you will often need some particular information about the current user. You can access the currently logged in user using AuthComponent::user(). This method is static, and can be used globally after the AuthComponent has been loaded. You can access it both as an instance method or as a static method:

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

// From inside a controller
$this->Auth->user('id');

You should be able to do something like:

// layout
<?php if(AuthComponent::user('name')): ?>
    Welcome <?php echo AuthComponent::user('name'); ?>
<?php else: ?>
    Welcom anon, Log in?
<?php endif; ?>
like image 152
Hoff Avatar answered Sep 30 '22 19:09

Hoff