MCPInstall

laravel-authorization-patterns

Best practices for Laravel authorization including Gates, Policies, middleware auth, and Blade directives for access control.

Installs
93
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-authorization-patterns
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads laravel-authorization-patterns automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Laravel Authorization Patterns

Gates for General Ability Checks

// In AuthServiceProvider or AppServiceProvider boot()
use Illuminate\Support\Facades\Gate;

Gate::define('access-admin', function (User $user) {
    return $user->is_admin;
});

Gate::define('manage-settings', function (User $user) {
    return $user->hasRole('admin');
});

// Usage
if (Gate::allows('access-admin')) {
    // ...
}

// ✅ Abort if unauthorized
Gate::authorize('access-admin'); // Throws AuthorizationException

// ✅ Check for specific user
Gate::forUser($otherUser)->allows('access-admin');

Policies for Model-Based Authorization

<?php

namespace App\Policies;

use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;

class PostPolicy
{
    // Runs before all other checks - return null to fall through
    public function before(User $user, string $ability): ?bool
    {
        if ($user->is_super_admin) {
            return true;
        }

        return null; // Fall through to specific method
    }

    public function viewAny(User $user): bool
    {
        return true;
    }

    public function view(User $user, Post $post): bool
    {
        return $post->is_published || $user->id === $post->user_id;
    }

    public function create(User $user): bool
    {
        return $user->hasVerifiedEmail();
    }

    public function update(User $user, Post $post): bool
    {
        return $user->id === $post->user_id;
    }

    public function delete(User $user, Post $post): Response
    {
        if ($user->id !== $post->user_id) {
            return Response::deny('You do not own this post.');
        }

        if ($post->is_published) {
            return Response::denyWithStatus(403, 'Published posts cannot be deleted.');
        }

        return Response::allow();
    }
}

Policies are auto-discovered when they follow the App\Policies\{Model}Policy convention.

Response Objects

use Illuminate\Auth\Access\Response;

// ✅ Rich authorization responses
public function publish(User $user, Post $post): Response
{
    if (! $user->hasVerifiedEmail()) {
        return Response::denyWithStatus(403, 'Verify your email first.');
    }

    if ($post->user_id !== $user->id) {
        return Response::denyAsNotFound(); // Returns 404 instead of 403
    }

    return Response::allow();
}

// Inspecting responses without exceptions
$response = Gate::inspect('publish', $post);

if ($response->allowed()) {
    // Publish the post
} else {
    echo $response->message();
}

Middleware Authorization

// ✅ Route-level authorization
Route::put('/posts/{post}', [PostController::class, 'update'])
    ->can('update', 'post');

Route::resource('posts', PostController::class)
    ->middleware('can:viewAny,App\Models\Post')
    ->only(['index']);

// ✅ Route group with gate
Route::middleware('can:access-admin')->group(function () {
    Route::get('/admin/dashboard', [AdminController::class, 'index']);
    Route::get('/admin/users', [AdminController::class, 'users']);
});

Blade Directives

{{-- ✅ Single ability check --}}
@can('update', $post)
    <a href="{{ route('posts.edit', $post) }}">Edit</a>
@endcan

{{-- ✅ Multiple abilities --}}
@canany(['update', 'delete'], $post)
    <div class="actions">
        @can('update', $post)
            <button>Edit</button>
        @endcan
        @can('delete', $post)
            <button>Delete</button>
        @endcan
    </div>
@endcanany

{{-- ✅ Inverse check --}}
@cannot('create', App\Models\Post::class)
    <p>You do not have permission to create posts.</p>
@endcannot

{{-- ✅ Gate check --}}
@can('access-admin')
    <a href="/admin">Admin Panel</a>
@endcan

Form Request authorize() Integration

class UpdatePostRequest extends FormRequest
{
    // ✅ Combine validation with authorization
    public function authorize(): bool
    {
        return $this->user()->can('update', $this->route('post'));
    }

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:255'],
            'content' => ['required', 'string'],
        ];
    }
}

Controller Authorization

class PostController extends Controller
{
    public function index()
    {
        // ✅ Authorize against model class
        $this->authorize('viewAny', Post::class);

        return Post::paginate();
    }

    public function update(UpdatePostRequest $request, Post $post)
    {
        // ✅ Authorize against model instance
        $this->authorize('update', $post);

        $post->update($request->validated());

        return new PostResource($post);
    }

    // ❌ Don't check authorization with manual if statements
    public function destroy(Post $post)
    {
        if (auth()->id() !== $post->user_id) {
            abort(403);
        }
        // Skips policy, no reuse, harder to test
    }

    // ✅ Use policy
    public function destroy(Post $post)
    {
        $this->authorize('delete', $post);

        $post->delete();

        return response()->noContent();
    }
}

Testing Authorization

use Illuminate\Support\Facades\Gate;

// ✅ Test policy methods directly
public function test_user_can_update_own_post(): void
{
    $user = User::factory()->create();
    $post = Post::factory()->for($user)->create();

    $this->assertTrue($user->can('update', $post));
}

public function test_user_cannot_update_others_post(): void
{
    $user = User::factory()->create();
    $post = Post::factory()->create(); // Different user

    $this->assertFalse($user->can('update', $post));
}

// ✅ Test via HTTP
public function test_unauthorized_user_gets_403(): void
{
    $user = User::factory()->create();
    $post = Post::factory()->create();

    $this->actingAs($user)
        ->putJson("/api/posts/{$post->id}", ['title' => 'New Title'])
        ->assertForbidden();
}

// ✅ Bypass authorization in other tests
public function test_post_update_logic(): void
{
    Gate::before(fn () => true); // Allow everything

    // Test business logic without auth concerns
}

Checklist

  • Gates used for general abilities not tied to a model
  • Policies used for all model-based authorization
  • Policies follow auto-discovery naming convention
  • before() returns null to fall through (not false)
  • Response objects used for detailed denial messages
  • Authorization applied via middleware, Form Request, or controller
  • Blade directives used for conditional UI rendering
  • No manual if/abort(403) checks bypassing policies
  • Authorization logic tested for allowed and denied cases
  • Gate::inspect() used when response message is needed

FAQ

What does the laravel-authorization-patterns skill do?

Best practices for Laravel authorization including Gates, Policies, middleware auth, and Blade directives for access control.

How do I install laravel-authorization-patterns?

Run npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-authorization-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/laravel-authorization-patterns/ (personal) or .claude/skills/laravel-authorization-patterns/ (project).

Which AI agents can use laravel-authorization-patterns?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is laravel-authorization-patterns safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains laravel-authorization-patterns?

It is published by iserter in iserter/laravel-claude-agents. It has 93 recorded installs.

More from iserter/laravel-claude-agents

View all →

eloquent-best-practices

iserter/laravel-claude-agents

Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

laravel-tdd

iserter/laravel-claude-agents

Test-Driven Development specifically for Laravel applications using Pest PHP. Use when implementing any Laravel feature or bugfix - write the test first, watch it fail, write minimal code to pass.

Backend & APIs378 installs

laravel-blade-component-patterns

iserter/laravel-claude-agents

Best practices for Laravel Blade components including class-based and anonymous components, slots, attribute bags, and reusable UI patterns.

Backend & APIs116 installs

api-resource-patterns

iserter/laravel-claude-agents

Best practices for Laravel API Resources including resource transformation, collection handling, conditional attributes, and relationship loading.

Backend & APIs110 installs

laravel-systematic-debugging

iserter/laravel-claude-agents

Systematic debugging process for Laravel applications - ensures root cause investigation before attempting fixes. Use for any Laravel issue (test failures, bugs, unexpected behavior, performance problems).

Backend & APIs102 installs

laravel-validation-patterns

iserter/laravel-claude-agents

Best practices for Laravel validation including Form Requests, custom rules, conditional validation, and input sanitization.

Backend & APIs100 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs