Laravel Security Authorization: Writing Policies

Policy Methods

  • <?php namespace App\Policies; use App\User; use App\Post; class PostPolicy { /** * Determine if the given post can be updated by the user. * * @param \App\User $user * @param \App\Post $post * @return bool */ public function update(User $user, Post $post) { return $user->id === $post->user_id; } }.

Methods Without Models

/**
 * Determine if the given user can create posts.
 *
 * @param  \App\User  $user
 * @return bool
 */
public function create(User $user)
{
    //
}

Some policy methods only receive the currently authenticated user and not an instance of the model they authorize.

Guest Users

<?php

namespace App\Policies;

use App\User;
use App\Post;

class PostPolicy
{
    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(?User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

Policy Filters

Public function before($user, $ability)
{
    if ($user->isSuperAdmin()) {
        return true;
    }
}

Laravel Security Authorization: Writing Policies — Structure map

Clickable & Draggable!

Laravel Security Authorization: Writing Policies — Related pages: