Security with Laravel

Table of Contents

# Policies

API Platform is compatible with Laravel’s authorization mechanism.

To utilize policies in API Platform, it is essential to have Laravel’s authentication system initialized. See the Authentication section for more information.

Once a gate is defined, API Platform will automatically detect your policy.

// app/Models/Book.php

use ApiPlatform\Metadata\Patch;

#[Patch]
class Book extends Model
{
}

API Platform will detect the operation and map it to a specific method in your policy according to the rules defined in this table:

OperationPolicy
GET collectionviewAny
GETview
POSTcreate
PATCHupdate
DELETEdelete
PUTupdate or create if the resource doesn’t already exist

If your policy methods do not match Laravel’s conventions, you can always use the policy property on an operation attribute to enforce this policy:

// app/Models/Book.php
namespace App\Models;

 use ApiPlatform\Metadata\ApiResource;
+use ApiPlatform\Metadata\Patch;
 use Illuminate\Database\Eloquent\Model;

-#[ApiResource]
 #[ApiResource(
     paginationItemsPerPage: 10,
+    operations: [
+       new Patch(
+            policy: 'myCustomPolicy',
+       ),
+    ],
)]
 class Book extends Model
 {
 }

You also can link a model to a policy:

use App\Models\Book;
use App\Tests\Book\BookPolicy;
use Illuminate\Support\Facades\Gate;

Gate::guessPolicyNamesUsing(function (string $modelClass): ?string {
    return Book::class === $modelClass ?
        BookPolicy::class :
        null;
});

# Authentication

Usually, you will use Sanctum and add a middleware on secured routes:

// app/Models/Book.php

use ApiPlatform\Metadata\Patch;

#[Patch(middleware: 'auth:sanctum')]
class Book extends Model
{
}

Or you can define it globally in the configuration by adding the following code:

<?php
// config/api-platform.php
return [
    // ....
    'defaults' => [
        // ....
        'middleware' => 'auth:sanctum',
    ],
];

You can also help us improve the documentation of this page.

Made with love by

Les-Tilleuls.coop can help you design and develop your APIs and web projects, and train your teams in API Platform, Symfony, Next.js, Kubernetes and a wide range of other technologies.

Learn more

Copyright © 2023 Kévin Dunglas

Sponsored by Les-Tilleuls.coop