Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4: protecting routes provided by a controller

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!

like image 743
Josh Avatar asked Jul 07 '13 13:07

Josh


2 Answers

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');
});
like image 91
Markus Hofmann Avatar answered Sep 22 '22 01:09

Markus Hofmann


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')));
    }
like image 24
Melvin Avatar answered Sep 19 '22 01:09

Melvin