简体   繁体   中英

Laravel: beforeFilter used in BaseController construct doesn't work in subclasses

I read Laravel's documentation covering controller filters . I wish to correctly apply this functionality to my BaseController , so all controllers that extend it can run the beforeFilter automatically. Two of the routes, however, need to be excluded. The excluded routes are named home and logout , but the code below doesn't work: the customFilter is ignored by classess extending BaseController. What am I doing wrong?

routes.php:

Route::get('/',
    array(
        'before' => 'auth',
        'uses' => 'DefaultController@index',
        'as' => 'home'
        )
    );

Route::get('/logout',
    array(
        'before' => 'auth',
        'uses' => 'UserController@logout',
        'as' => 'logout'
        )
    );

Route::get('/profile',
    array(
        'before' => 'auth',
        'uses' => 'UserController@profile',
        'as' => 'profile'
        )
    );

/// And so on...

BaseController.php:

<?php

    class BaseController extends Controller {

        // beforeFilter to be inherited by subclasses
        public function __construct() {
            $this->beforeFilter('customFilter', array('except' => array('home', 'logout')));
        }

        // Rest of the code

    }

?>

and later (for example) :

<?php

class UserController extends BaseController {

    // Code...

}

?>

You have to construct parent in the child class like this:

class UserController extends BaseController {

   public function __construct(){
     parent::__construct();
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM