5
votes

I'm building a Laravel 4 app and I want to protect my admin area so it is only accessible if the user is logged in/authenticated.

What is the best way to do this?

The Laravel docs say you can protect a route like this:

Route::get('profile', array('before' => 'auth', function()
{
// Only authenticated users may enter...
}));

But what happens when my route looks like this:

Route::resource('cms', 'PostsController');

How do I protect a route that is directing to a controller?

Thanks in advance!

3

3 Answers

18
votes

You could use Route Groups for this purpose.

So for example:

Route::group(array('before' => 'auth'), function()
{
    Route::get('profile', function()
    {
        // Has Auth Filter
    });

    Route::resource('cms', 'PostsController');

    // You can use Route::resource togehter with 
    // direct routes to the Resource Controller
    // so e.g. Route::post('cms', 'PostsController@save');
});
3
votes

You can put the filter on the constructor of your Controller like this:

public function __construct()
    {
        $this->beforeFilter('auth');

        $this->beforeFilter('csrf', array('on' => 'post'));

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

In your PostsController you can put a closure in the constructor to do the same before logic as the previous route.

    public function __construct()
    {
        $this->beforeFilter(function()
        {
            //
        });
    }