How to apply a beforeFilter to certain actions only

Published on and tagged with cakephp  faq  tip

If you define a beforeFilter in your controller, it will be executed before each action. Sometimes, that behaviour is not desired, and you want to exclude an action from the application of the beforeFilter. The following simple example gives you an idea of how to accomplish that:

// app/controllers/users_controller.php
class UsersController extends AppController
    function beforeFilter()
        if ($this->action != 'login')
            // execute beforeFilter logic

    function login()
        // do login

    function edit($id)
        // do edit

    function delete($id)
        // do delete

5 comments baked

  • ianh

    Useful stuff thanks. Is there a similar way to stop custom functions (especially beforeSave()) from being called in your model?

  • JP

    something I use in my controllers…
    function beforeFilter(){
    $excludeBeforeFilter = array(‘view’,’index’);
    if (!in_array($this->action,$excludeBeforeFilter)){
    Just add any other actions you want to exclude from validation to the array.

  • Sandy

    Nice tip thanks! I’ve used cakephp exclusively for my project.. this little tip will come in very handy.

  • sidhu

    bro i have a problem in call back before filter
    Logic is that:

    public function beforeFilter(){
            $this->Auth->allow( 'signup' );
            if( $this->Auth->user('role') == 'admin' || $this->Auth->user('role') == 'sub_user' ){
                if( isset( $_GET['search'] ) ){
                    $this->redirect( array( 'controller' => 'users' , 'action' => 'searchContent/?search='.$_GET['search'] ) );

    when $search is exists it shows error like:

    This web page has a redirect loop

  • cakebaker

    @sidhu: Well, you get this error because there is an endless loop: if there is a search param, you redirect to an action and provide a search param. But this will again trigger the redirect in the beforeFilter() and so on. You have to define some additional condition(s) to break this loop.

© daniel hofstetter. Licensed under a Creative Commons License