Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 authentication. Restrict access to some functions of a resource but not all

I have this blog resource which has the usual CRUD methods.(index, create, store, show, edit, update, destroy).

I have the following route in my routes.php:

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

but I want to restrict all but index and show. so I have

Route::get('blog', 'PostsController@index');
Route::group(array('before' => 'auth'), function()
{
    Route::resource('blog', 'PostsController');
});

which is fine for index but I don't know how to route the show method ? Or is there another way? Instead of routing the resource should I route every URI individually and put the ones I want restricted in my restricted access route?

Cheers

like image 582
Ben Dubuisson Avatar asked Sep 05 '13 21:09

Ben Dubuisson


1 Answers

Laravel has a feature that lets you specify filters in the controllers' __construct method using $this->beforeFilter. This function takes a second argument that lets your provide exceptions (or enable the filter only for certain methods). Try using your original routes file and set up your controller like this:

class PostsController extends BaseController {

    function __construct() {
        // ...
        $this->beforeFilter('auth', array('except' => array('index', 'show')));
        // ...
    }

    // ...

See Controller Filters in the Laravel documentation. It's not entirely well-documented, but you can also start a deeper journey into the guts of Laravel from here.

like image 118
Jon Gjengset Avatar answered Oct 13 '22 13:10

Jon Gjengset