Laravel 4 except filter in controller constructor

巧了我就是萌 提交于 2019-12-07 06:50:38

问题


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');

回答1:


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'));
    }
}



回答2:


Yes, it's possible, because there is an public $except; and public $only; property in Filter class in vendor/laravel/framework/src/Illuminate/Routing/Controllers/Filter.php file and you can also use only instead of except to use a filter only on specific methods.

From L4 docs for only

 $this->afterFilter('log', array('only' => array('fooAction', 'barAction')));

So, this should work too

$this->beforeFilter('log', array('except' => array('fooAction', 'barAction')));

In L3 I've used

$this->filter('before', 'auth')->except(array('login', 'login_ajax', 'fb_login'));

but didn't use in L4 but it should work, according to source code and the doc.



来源:https://stackoverflow.com/questions/17076011/laravel-4-except-filter-in-controller-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!