laravel 4 filter route not working

- 1 answer

Ad

I have an admin section in my app which works fine, however now I want to close it so only admin has access. Basically I want to redirect to admin/login if a non-admin person is trying to access admin pages.

This is my admin route (which works):

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

I tried adding the following filter above the admin controller route, and I also commented out the local array element so the environment is set to production, but it is just not working.

Routes.php

Route::filter('isAdmin', function()
{
    if ( ! Session::has('admin') ) {
        return Redirect::to('admin/login');
    }
});

Route::get('admin', array('before' => 'isAdmin', function() 
{
    echo 'You are over 200 years old!';
}));

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

So if now I go to mysite/admin , I still get to admin dashboard even though session admin does not exist.

Ad

Answer

Ad

Something like this should work, this is untested

Filters.php

Route::filter('isAdmin', function()
{
    if ( ! Session::has('admin'))
    {
        return Redirect::to('admin/login');
    }
});

Routes.php

Route::group(['before' => 'isAdmin'], function() 
{
    Route::get('admin', '[email protected]');
});

AdminController.php

<?php
class AdminController
{
    public function index()
    {
        echo 'they\'re an admin';
    }
}
Ad
source: stackoverflow.com
Ad