Protecting all admin/ routes with auth in Laravel

Yev picture Yev · Apr 5, 2013 · Viewed 22.1k times · Source

I am brand new to laravel and am setting up admin panel authorization on my first application. The way I have my files setup currently setup is:

controllers/
    admin/
        dashboard.php
        settings.php
    non-admin-controller1.php
    non-admin-controller1.php
views/
    admin/
        dashboard.blade.php
        login.blade.php
        template.blade.php
    non-admin-view1.php
    non-admin-view1.php
    non-admin-view1.php

...and these are my routes

Route::get('admin/login', function()
{
    return View::make('admin.login');
});

Route::get('admin/logout', function()
{
    return Auth::logout();
    return Redirect::to('admin/login');
});

Route::post('admin/login', function()
{
    $userdata = array('username' => Input::get('username'),
                      'password' => Input::get('password'));
    
    if (Auth::attempt($userdata))
    {
        return Redirect::to('admin');
    }
    else
    {
        return Redirect::to('admin/login')->with('login_errors',true);
    }
});

Route::controller('admin.dashboard');

Route::get('admin', array('before' => 'auth', function() {
    return Redirect::to_action('admin@dashboard');
}));

Route::filter('auth', function()
{
    if (Auth::guest()) return Redirect::to('admin/login');
});

When I go to /admin I am redirected to admin/login and asked to login which is exactly how I need it to work. Upon logging in I am redirected to admin/dashboard and it all looks good there too. I am having 2 problems however.

  1. When I go to admin/logout I am logged out but greeted with a blank page (it's not redirecting to admin/login)

  2. When logged out, if I go to admin/dashboard I am greeted with the error

Error rendering view: [admin.dashboard]

Trying to get property of non-object

What am I doing wrong here? What am I doing right? Would it make more sense to create a separate bundle for admin? Thanks!

Answer

Yev picture Yev · Apr 7, 2013

So I was able to solve my problem a slightly different way. I created an (base) Admin_Controller in the root of the controllers folder, with a constructor calling the auth filter before execution:

class Admin_Controller extends Base_Controller {

    public function __construct()
    {
        $this->filter('before', 'auth');
    }

}

and then made all my admin related controllers in /controllers/admin extend Admin_Controller and call the parent constructor:

class Admin_Dashboard_Controller extends Admin_Controller {

    public function __construct()
    {
        parent::__construct();
    }

    public function action_index()
    {
        return View::make('admin.dashboard');
    }

}

This might not be the most eloquent solution, but it does the job!