Skip to content

Commit

Permalink
Document authorizing resource controllers
Browse files Browse the repository at this point in the history
This apparently wasn't documented before.

Fixes https://github.com/laravel/docs/issues/4769
  • Loading branch information
driesvints committed Nov 23, 2018
1 parent 2af1b98 commit d3a9516
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions authorization.md
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,60 @@ In addition to helpful methods provided to the `User` model, Laravel provides a
}
}

#### Authorizing Resource Controllers

When authorizing resources through a resource controller you can make use of the `authorizeResource` method in the controller's constructor. This will allow you to fully protect the resource controller methods with a single line of code.

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller
{
public function __constructor()
{
$this->authorizeResource(Post::class, 'post');
}
}

This method will add the appropriate middleware which will map to same policy methods as your controller methods. The second parameter allows you to modify the argument name for the `can` middelware that will be bound but is not required. If it's not passed it'll be derived from the model name.

The subsequential policy would look as follows:

<?php

namespace App\Policies;

use App\User;
use App\Post;

class PostPolicy
{
public function view(User $user, Post $post)
{
// ...
}

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

public function update(User $user, Post $post)
{
// ...
}

public function delete(User $user, Post $post)
{
// ...
}
}

#### Actions That Don't Require Models

As previously discussed, some actions like `create` may not require a model instance. In these situations, you may pass a class name to the `authorize` method. The class name will be used to determine which policy to use when authorizing the action:
Expand Down

0 comments on commit d3a9516

Please sign in to comment.