Authorization

    In addition to providing authentication services out of the box, Laravel also provides a simple way to authorize user actions against a given resource. Like authentication, Laravel's approach to authorization is simple, and there are two primary ways of authorizing actions: gates and policies.

    Think of gates and policies like routes and controllers. Gates provide a simple, Closure based approach to authorization while policies, like controllers, group their logic around a particular model or resource. We'll explore gates first and then examine policies.

    You do not need to choose between exclusively using gates or exclusively using policies when building an application. Most applications will most likely contain a mixture of gates and policies, and that is perfectly fine! Gates are most applicable to actions which are not related to any model or resource, such as viewing an administrator dashboard. In contrast, policies should be used when you wish to authorize an action for a particular model or resource.

    Gates are Closures that determine if a user is authorized to perform a given action and are typically defined in the class using the Gate facade. Gates always receive a user instance as their first argument, and may optionally receive additional arguments such as a relevant Eloquent model:

    Gates may also be defined using a style callback string, like controllers:

    1. /**
    2. * Register any authentication / authorization services.
    3. *
    4. * @return void
    5. */
    6. public function boot()
    7. {
    8. $this->registerPolicies();
    9. Gate::define('update-post', 'App\Policies\[email protected]');
    10. }

    Resource Gates

    You may also define multiple Gate abilities at once using the resource method:

    1. Gate::resource('posts', 'App\Policies\PostPolicy');

    This is identical to manually defining the following Gate definitions:

    1. Gate::define('posts.view', 'App\Policies\[email protected]');
    2. Gate::define('posts.create', 'App\Policies\');
    3. Gate::define('posts.update', 'App\Policies\[email protected]');
    4. Gate::define('posts.delete', 'App\Policies\');

    By default, the view, create, update, and delete abilities will be defined. You may override or add to the default abilities by passing an array as a third argument to the resource method. The keys of the array define the names of the abilities while the values define the method names. For example, the following code will create two new Gate definitions - posts.image and posts.photo:

    1. Gate::resource('posts', 'PostPolicy', [
    2. 'image' => 'updateImage',
    3. 'photo' => 'updatePhoto',
    4. ]);

    Authorizing Actions

    To authorize an action using gates, you should use the allows or denies methods. Note that you are not required to pass the currently authenticated user to these methods. Laravel will automatically take care of passing the user into the gate Closure:

    1. if (Gate::allows('update-post', $post)) {
    2. // The current user can update the post...
    3. }
    4. if (Gate::denies('update-post', $post)) {
    5. // The current user can't update the post...
    6. }

    If you would like to determine if a particular user is authorized to perform an action, you may use the forUser method on the Gate facade:

    1. if (Gate::forUser($user)->allows('update-post', $post)) {
    2. // The user can update the post...
    3. }
    4. // The user can't update the post...
    5. }

    Generating Policies

    Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a Post model and a corresponding PostPolicy to authorize user actions such as creating or updating posts.

    The make:policy command will generate an empty policy class. If you would like to generate a class with the basic "CRUD" policy methods already included in the class, you may specify a —model when executing the command:

    1. php artisan make:policy PostPolicy --model=Post

    Once the policy exists, it needs to be registered. The AuthServiceProvider included with fresh Laravel applications contains a policies property which maps your Eloquent models to their corresponding policies. Registering a policy will instruct Laravel which policy to utilize when authorizing actions against a given model:

    1. <?php
    2. namespace App\Providers;
    3. use App\Post;
    4. use App\Policies\PostPolicy;
    5. use Illuminate\Support\Facades\Gate;
    6. use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
    7. class AuthServiceProvider extends ServiceProvider
    8. {
    9. /**
    10. * The policy mappings for the application.
    11. *
    12. * @var array
    13. */
    14. protected $policies = [
    15. Post::class => PostPolicy::class,
    16. ];
    17. /**
    18. * Register any application authentication / authorization services.
    19. *
    20. * @return void
    21. */
    22. public function boot()
    23. $this->registerPolicies();
    24. //
    25. }
    26. }

    Policy Methods

    Once the policy has been registered, you may add methods for each action it authorizes. For example, let's define an update method on our PostPolicy which determines if a given User can update a given Post instance.

    The update method will receive a User and a Post instance as its arguments, and should return true or false indicating whether the user is authorized to update the given Post. So, for this example, let's verify that the user's id matches the user_id on the post:

    1. <?php
    2. namespace App\Policies;
    3. use App\User;
    4. use App\Post;
    5. class PostPolicy
    6. {
    7. /**
    8. * Determine if the given post can be updated by the user.
    9. *
    10. * @param \App\User $user
    11. * @param \App\Post $post
    12. * @return bool
    13. */
    14. public function update(User $user, Post $post)
    15. {
    16. return $user->id === $post->user_id;
    17. }
    18. }

    You may continue to define additional methods on the policy as needed for the various actions it authorizes. For example, you might define view or delete methods to authorize various Post actions, but remember you are free to give your policy methods any name you like.

    Methods Without Models

    Some policy methods only receive the currently authenticated user and not an instance of the model they authorize. This situation is most common when authorizing create actions. For example, if you are creating a blog, you may wish to check if a user is authorized to create any posts at all.

    When defining policy methods that will not receive a model instance, such as a create method, it will not receive a model instance. Instead, you should define the method as only expecting the authenticated user:

    1. /**
    2. * Determine if the given user can create posts.
    3. *
    4. * @param \App\User $user
    5. * @return bool
    6. */
    7. public function create(User $user)
    8. {
    9. //
    10. }

    For certain users, you may wish to authorize all actions within a given policy. To accomplish this, define a before method on the policy. The before method will be executed before any other methods on the policy, giving you an opportunity to authorize the action before the intended policy method is actually called. This feature is most commonly used for authorizing application administrators to perform any action:

    1. public function before($user, $ability)
    2. {
    3. return true;
    4. }
    5. }

    If you would like to deny all authorizations for a user you should return false from the before method. If null is returned, the authorization will fall through to the policy method.

    Via The User Model

    The User model that is included with your Laravel application includes two helpful methods for authorizing actions: can and cant. The can method receives the action you wish to authorize and the relevant model. For example, let's determine if a user is authorized to update a given Post model:

    1. if ($user->can('update', $post)) {
    2. //
    3. }

    If a for the given model, the can method will automatically call the appropriate policy and return the boolean result. If no policy is registered for the model, the can method will attempt to call the Closure based Gate matching the given action name.

    Actions That Don't Require Models

    Remember, some actions like create may not require a model instance. In these situations, you may pass a class name to the can method. The class name will be used to determine which policy to use when authorizing the action:

    Via Middleware

    Laravel includes a middleware that can authorize actions before the incoming request even reaches your routes or controllers. By default, the Illuminate\Auth\Middleware\Authorize middleware is assigned the key in your App\Http\Kernel class. Let's explore an example of using the can middleware to authorize that a user can update a blog post:

    1. use App\Post;
    2. Route::put('/post/{post}', function (Post $post) {
    3. // The current user may update the post...
    4. })->middleware('can:update,post');

    In this example, we're passing the can middleware two arguments. The first is the name of the action we wish to authorize and the second is the route parameter we wish to pass to the policy method. In this case, since we are using , a Post model will be passed to the policy method. If the user is not authorized to perform the given action, a HTTP response with a 403 status code will be generated by the middleware.

    Actions That Don't Require Models

    Again, some actions like create may not require a model instance. In these situations, you may pass a class name to the middleware. The class name will be used to determine which policy to use when authorizing the action:

    1. Route::post('/post', function () {
    2. // The current user may create posts...
    3. })->middleware('can:create,App\Post');

    In addition to helpful methods provided to the User model, Laravel provides a helpful authorize method to any of your controllers which extend the App\Http\Controllers\Controller base class. Like the can method, this method accepts the name of the action you wish to authorize and the relevant model. If the action is not authorized, the authorize method will throw an Illuminate\Auth\Access\AuthorizationException, which the default Laravel exception handler will convert to an HTTP response with a 403 status code:

    1. <?php
    2. namespace App\Http\Controllers;
    3. use App\Post;
    4. use Illuminate\Http\Request;
    5. use App\Http\Controllers\Controller;
    6. class PostController extends Controller
    7. {
    8. /**
    9. * Update the given blog post.
    10. *
    11. * @param Request $request
    12. * @param Post $post
    13. * @return Response
    14. */
    15. public function update(Request $request, Post $post)
    16. {
    17. $this->authorize('update', $post);
    18. // The current user can update the blog post...
    19. }
    20. }

    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:

    1. /**
    2. * Create a new blog post.
    3. *
    4. * @param Request $request
    5. * @return Response
    6. */
    7. public function create(Request $request)
    8. {
    9. $this->authorize('create', Post::class);
    10. // The current user can create blog posts...
    11. }

    Via Blade Templates

    When writing Blade templates, you may wish to display a portion of the page only if the user is authorized to perform a given action. For example, you may wish to show an update form for a blog post only if the user can actually update the post. In this situation, you may use the @can and @cannot family of directives:

    1. @can('update', $post)
    2. <!-- The Current User Can Update The Post -->
    3. @elsecan('create', App\Post::class)
    4. <!-- The Current User Can Create New Post -->
    5. @endcan
    6. @cannot('update', $post)
    7. <!-- The Current User Can't Update The Post -->
    8. @elsecannot('create', App\Post::class)
    9. <!-- The Current User Can't Create New Post -->
    10. @endcannot

    These directives are convenient shortcuts for writing @if and @unless statements. The @can and @cannot statements above respectively translate to the following statements:

    1. @if (Auth::user()->can('update', $post))
    2. <!-- The Current User Can Update The Post -->
    3. @endif
    4. @unless (Auth::user()->can('update', $post))
    5. <!-- The Current User Can't Update The Post -->
    6. @endunless

    Actions That Don't Require Models

    Like most of the other authorization methods, you may pass a class name to the and @cannot directives if the action does not require a model instance: