Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I use ACL middleware with RESTful Resource controllers
    Laravel ACL middleware RESTful Resource controllers Laravel middleware Blade directives Laravel permissions


Can I use ACL middleware with RESTful Resource controllers


Yes, you can use ACL middleware with RESTful Resource controllers in Laravel. Here's how you can implement it:

1. Apply the ACL middleware to the controller's constructor:

php
public function __construct()
{
    $this->middleware('acl');
}

This will apply the `acl` middleware to all methods in the controller.

2. Specify which methods to protect with the middleware:

php
public function __construct()
{
    $this->middleware('acl', ['only' => ['create', 'store', 'edit', 'update', 'destroy']]);
}

This will only apply the `acl` middleware to the `create`, `store`, `edit`, `update`, and `destroy` methods.

3. Exclude specific methods from the middleware:

php
public function __construct()
{
    $this->middleware('acl', ['except' => ['index', 'show']]);
}

This will apply the `acl` middleware to all methods except `index` and `show`.

4. Pass permissions as parameters to the middleware:

php
Route::resource('posts', 'PostController');

In your `PostController`, you can apply the middleware with permissions:

php
public function __construct()
{
    $this->middleware('acl:create-post', ['only' => ['create', 'store']]);
    $this->middleware('acl:edit-post', ['only' => ['edit', 'update']]);
    $this->middleware('acl:delete-post', ['only' => ['destroy']]);
}

This will protect the `create`, `store`, `edit`, `update`, and `destroy` methods with the corresponding permissions.

5. Use the `@can` and `@cannot` Blade directives to conditionally display content based on the user's permissions:

html
@can('create-post')
    <a href="{{ route('posts.create') }}">Create Post</a>
@endcan

By following these steps and leveraging the flexibility of Laravel's middleware and RESTful Resource controllers, you can effectively integrate ACL functionality into your application's routes and controllers.

Citations:
[1] https://github.com/rohsyl/laravel-acl
[2] https://github.com/kodeine/laravel-acl
[3] https://heera.it/laravel-5-1-x-acl-middleware
[4] https://laracasts.com/discuss/channels/laravel/laravel-role-permission-with-inbuilt-acl-gui
[5] https://stackoverflow.com/questions/38884533/permissions-in-laravel-acl-vs-middleware