Amaynut
Amaynut

Reputation: 4271

Laravel Add a filter to resourceful route

I'm using Laravel 4.2 I have a ressourceful route like this:

Route::resource('customers', 'CustomersController');

How can I add a filter, let's say 'auth' filter to all corresponding routes and how to target only some of them, let's say I want only to filter access to the named route 'customers.create'.

Upvotes: 2

Views: 672

Answers (1)

Vytautas Lozickas
Vytautas Lozickas

Reputation: 226

You can define a filter in your Controller's constructor:

public function __construct()
{
    $this->beforeFilter('auth', ['only' => ['update', 'store']]);
}

If you have many resources you can use route groups:

Route::group(['before'=>'auth'], function () {
    Route::resource('customers', 'CustomersController');
    // ... another resource ...
});

...and specify beforeFilter in each Controller's constructor.

OR:

  • Use a simple if statement in routes.php:

    if (Auth::check()) {
        Route::resource('customers', 'CustomersController');
    } else {
        Route::resource('customers', 'CustomersController', ['except' => ['update', 'store']]);
    }
    
  • Create a base controller for resources that use the same filter and extend it:

    class AuthorizedController extends BaseController {
        // ... constructor with beforeFilter definition ...
    }
    
    class CustomersController extends AuthorizedController { ... }
    

Upvotes: 1

Related Questions