• Developer New

    Wednesday, March 15, 2017

    Registering Before Filters On a Controller

    Registering Before Filters On a Controller

    Problem

    You want a filter to occur before any actions on a specific controller.
    You thought about adding to app/filters.php, but are curious if there's another way to do this.

    Solution

    Use Controller::beforeFilter()
    This is normally done in the constructor of your controller.
    class MyController extends \Controller
    {
        public function __construct()
        {
            $this->beforeFilter('auth');
        }
    }
    Just like Route filters, you can add additional arguments.
    class MyController extends \Controller
    {
        public function __construct()
        {
            $this->beforeFilter('auth', ['except' => 'login']);
            $this->beforeFilter('csrf', ['on' => 'post']);
        }
    }
    Or implement the filter with a Closure.
    class MyController extends \Controller
    {
        public function __construct()
        {
            $this->beforeFilter(function()
            {
                if (date('G') < 6)
                {
                    return "This website doesn't work before 6am";
                }
            });
        }
    }

    No comments:

    Post a Comment

    Fashion

    Beauty

    Travel