简体   繁体   中英

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!

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');
});

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')));
    }

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()
        {
            //
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM