Laravel 4 except the filter in the controller constructor

I currently have an AdminContoller with a constructor method that handles some of the earlier filters. Is there a way to filter before all controller methods except one?

I use Entrust for roles and permissions, but this code throws me into an endless redirection loop. I have not logged in as a user at all. Therefore, this code should redirect me to the URL / admin / login, which is attached to the unfiltered AdminController @adminLogin method. But is that not so?

// File AdminController.php

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 '); 
+4
source share
2 answers

As you added a new method to the resourceful controller, you must first register a new method before the resource.

eg.

 <?php // Routes.php Route::get('/admin/login', ' AdminController@adminLogin '); Route::resource('admin', 'AdminController'); 

Thus, your filters should work the way you do it:

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

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

From L4 docs to 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 used

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

but was not used in L4 , but it should work according to the source code and the document.

+3
source

Source: https://habr.com/ru/post/1485890/


All Articles