Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 AdminController@adminLogin 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', 'AdminController@adminLogin');
like image 974
JasonMortonNZ Avatar asked Mar 24 '23 14:03

JasonMortonNZ


1 Answers

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', 'AdminController@adminLogin');
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'));
    }
}
like image 147
Thomas Clarkson Avatar answered Apr 05 '23 21:04

Thomas Clarkson