Ben Dubuisson
Ben Dubuisson

Reputation: 757

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

Upvotes: 6

Views: 4568

Answers (2)

Sam Deering
Sam Deering

Reputation: 368

In Laravel 5 you use middleware function instead like this:

$this->middleware('auth', array('except' => array('index', 'show')));

Upvotes: 0

Jon Gjengset
Jon Gjengset

Reputation: 4236

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.

Upvotes: 13

Related Questions