Laravel 4 except filter in controller constructor

Laravel 4 except filter in controller constructor

Currently I have an AdminContoller with a construct method handling some of the before filters. Is there a way to do a before filter on all controller methods except one?

I’m using Entrust for Roles and Permissions, but this code is throwing me into an infinite redirect loop. I’m not logged in as a user at all. So this code should redirect me to the /admin/login url which is attached to an unfiltered [email protected] method. But it doesn’t?

// AdminController.php file

class AdminController extends BaseController {

    function __construct() {

        // Is something like this possible?
        $this->beforeFilter('admin', array('except' => array('adminLogin')));
        $this->beforeFilter('csrf', array('on' => 'post'));
    }

    public function index()
    {
        return "Admin - Index";
    }

    public function adminLogin()
    {
        return "Admin Login Form";
    }

    // ... and many more methods
}

// Filter.php file

Route::filter('admin', function()
{
    if( !Entrust::hasRole('admin') ) // Checks the current user
    {
        return Redirect::to('/admin/login');
    }
});

// Routes.php file

Route::resource('admin', 'AdminController');

Route::get('/admin/login', '[email protected]');

As you’ve added a new method into a resourceful controller, you should register the new method first, before the resource.

E.g.

<?php // Routes.php

Route::get('/admin/login', 'AdminContro[email protected]');
Route::resource('admin', 'AdminController');

This way your before filters should work as you have then like this:

<?php // AdminController.php
   class AdminController extends BaseController {
     function __construct() {
       $this->beforeFilter('admin', array('except' => array('adminLogin')));
      $this->beforeFilter('csrf', array('on' => 'post'));
    }
}
.
.
.
.