Setting Layout for Users Logged In

If you have anything that you want to run or be available for every controller in your application, you'll need to copy the app_controller.php file from the cake folder to the app folder. User authentication, for example, could be in here (there is an authentication example on the wiki that describes this). One of the common things in an application where you have user authentication is that the layout itself will be different depending on whether you are logged in or not.

Normally, different layouts can be specified at the controller level:

var $layout = 'mylayout';

... or at the action level ...

$this->layout = 'mylayout';

This is all well and good and definitely offers a good level of flexibility in customizing the layout of the application based on the request. But because the code in app_controller gets called every time, you can use a beforeFilter (which executes before the action is called) to set the layout for you automatically.

function beforeFilter()
    $this->layout = 'loggedin';

This filter checks the Session to see if the user is logged in (based on the existence of a user in the session) and then sets the layout accordingly. Then, if you want to override beforeFilter at the individual controller level, just call the parent filter to make sure the code still gets called.

function beforeFilter()
  /* perform any controller specific work */
  parent::beforeFilter(); // call the parent method to set the layout automatically
Published October 16, 2006 · Updated October 16, 2006
Categorized as CakePHP
Short URL:


1 Comment · RSS feed
Marco Pegoraro said on September 10, 2007

I have implemented a more detailed system for changing layouts depending by group's apparteinance.

"Layout" name is stored in the Group model wich User is associated to. This way give me the chance to create different graphics for different applications by profiling users in groups.

A profiling system like othAuth will be helpfull to guarantee access control between applications!

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.

Want to learn about scaling CSS for large projects?

I'm available for full and half-day workshops on scalable CSS architecture. I can provide on-site training for your team. Interested?
Get in touch.