Policy Methods Automatically calling

Published 11 months ago by s4uron

It would be great if the policy methods get called automatically if they match the method name in the controller.

For example if I have the function

public function create() {
.....
}

in my controller i want the matching policy method

public function create(User $user) {
...
}

automatically to be called without writing

$this->authorize('create');

in every single method in my controller.

Where can I post this suggestion?

Regards s4uron

s4uron

push

thepassenger
martinbean

@s4uron You can already do this. If you look in the base controller class, you will see it imports a trait called AuthorizesRequests. This trait includes a method called authorizeResource() which will authorise all methods in a resource controller.

Example:

class ArticleController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(Article::class);
    }

    // Resource methods like index(), create(), store() etc.
}

The controller methods are mapped to policy methods like so:

  • show to view
  • create to create
  • store to create
  • edit to update
  • update to update
  • destroy to delete

So calling [email protected]() would invoke [email protected]() and so on.

s4uron

@martinbean Thanks a lot I will give it a try.

whats about index?

@thepassenger That would be an extra afford because I'm using

Route::resource(..)

thepassenger

@s4uron You could use the middleware in the controller constructor

public function __construct()
    {
        $this->middleware('can:create,updated,whatever');
    }

and limit to specific controller's action.

https://laravel.com/docs/5.4/controllers#controller-middleware

martinbean

@s4uron How would you authorize the index() action? It’s a listing of many resources, not just one.

Please sign in or create an account to participate in this conversation.