1
votes

In my Laravel app I have a resource route where I want to control access to individual routes based on a filter. I do this by declaring the resource with only the "view" routes and then declaring it again with only the "edit/create" routes in a nested filtered group. The filter is a custom one that check the logged-in user's capabilities.

My routes looks like this:

Route::group(['before' => 'auth'], function()
{
    $edit_routes = ['create', 'store', 'destroy', 'edit', 'update'];

    Route::resource('things', 'ThingsController', ['except' => $edit_routes]);

    // We'll filter the routes that involve editing resources
    Route::group(['before' => 'edit_resource'], function() use ($edit_routes) 
    {
        Route::resource('things', 'ThingsController', ['only' => $edit_routes]);
    });
}

Is this correct? It seems not to work, although no errors are thrown. When I visit a route in the nested filter (e.g. things/create) I just get a blank page.

Is there a better way of achieving this?

1

1 Answers

3
votes

Is this correct?

No

Is there a better way of achieving this?

Yes. Here is a great blog post by Phil Sturgeon that explains why you should just define each route manually.

If you really want to continue using the Resource Controller, you can apply the edit_resource inside the controller constructor like this:

Route::resource('things', 'ThingsController', ['before' => 'auth']);

Then in your resource controller

public function __construct()
{
    $this->beforeFilter('edit_resource', array('only' => ['create', 'store', 'destroy', 'edit', 'update']);
}