PHPackages                             sijot/api-guard - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. sijot/api-guard

ActiveLibrary[HTTP &amp; Networking](/categories/http)

sijot/api-guard
===============

A simple way of authenticating your APIs with API keys using Laravel

v3.1.3(9y ago)1461[2 PRs](https://github.com/Scouts-Sint-Joris/api-guard/pulls)PHPPHP &gt;=5.5.9

Since Jun 15Pushed 6y ago1 watchersCompare

[ Source](https://github.com/Scouts-Sint-Joris/api-guard)[ Packagist](https://packagist.org/packages/sijot/api-guard)[ Docs](https://github.com/chrisbjr/api-guard)[ RSS](/packages/sijot-api-guard/feed)WikiDiscussions master Synced 4w ago

READMEChangelog (1)Dependencies (14)Versions (30)Used By (0)

[![alt tag](https://github.com/Tjoosten/SVG-scss/raw/master/repo-assets/logo.jpg)](https://github.com/Tjoosten/SVG-scss/blob/master/repo-assets/logo.jpg)

A simple way of authenticating your APIs with API keys using Laravel. This package uses the following libraries:

- philsturgeon's [Fractal](https://github.com/thephpleague/fractal)
- maximebeaudoin's [api-response](https://github.com/ellipsesynergie/api-response)

Laravel 5.3 and 5.4 is finally supported!
-----------------------------------------

[](#laravel-53-and-54-is-finally-supported)

\*\*Laravel 5.3.x to 5.4.x: `~4.*`

\*\*Laravel 5.1.x to 5.2.x: [`~3.*`](https://github.com/chrisbjr/api-guard/blob/3.1/README.md)

\*\*Laravel 5.1.x: `~2.*`

\*\*Laravel 4.2.x: [`~1.*`](https://github.com/chrisbjr/api-guard/tree/laravel4) (Recently updated version for Laravel 4. Please note that there are namespace changes here)

\*\*Laravel 4.2.x: [`0.*`](https://github.com/chrisbjr/api-guard/tree/v0.7) (The version that most of you are using)

Quick start
-----------

[](#quick-start)

### Installation for Laravel 5.3 to 5.4

[](#installation-for-laravel-53-to-54)

Run `composer require chrisbjr/api-guard 4.*`

In your `config/app.php` add `Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider` to the end of the `providers` array

```
'providers' => array(

    ...
    Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider::class,
),
```

Now publish the migration and configuration files for api-guard:

```
$ php artisan vendor:publish --provider="Chrisbjr\ApiGuard\Providers\ApiGuardServiceProvider"

```

Then run the migration:

```
$ php artisan migrate

```

It will setup two tables - api\_keys and api\_logs.

### Generating your first API key

[](#generating-your-first-api-key)

Once you're done with the required setup, you can now generate your first API key.

Run the following command to generate an API key:

`php artisan api-key:generate`

Generally, the `ApiKey` object is a polymorphic object meaning this can belong to more than one other model.

To generate an API key that is linked to another object (a "user", for example), you can do the following:

`php artisan api-key:generate --id=1 --type=App\User`

To specify that a model can have API keys, you can attach the `Apikeyable` trait to the model:

```
class User extends Model
{
    use Apikeyable;

    ...
}
```

This will attach the following methods to the model:

```
// Get the API keys of the object
$user->apiKeys();

// Create an API key for the object
$user->createApiKey();
```

To generate an API key from within your application, you can use the following method in the `ApiKey` model:

```
$apiKey = Chrisbjr\ApiGuard\Models\ApiKey::make()

// Attach a model to the API key
$apiKey = Chrisbjr\ApiGuard\Models\ApiKey::make($model)
```

Usage
-----

[](#usage)

You can start using ApiGuard by simply attaching the `auth.apikey` middleware to your API route:

```
Route::middleware(['auth.apikey'])->get('/test', function (Request $request) {
    return $request->user(); // Returns the associated model to the API key
});
```

This effectively secures your API with an API key which needs to specified in the `X-Authorization` header. This can be configured in `config/apiguard.php`.

Here is a sample cURL command to demonstrate:

```
curl -X GET \
  http://apiguard.dev/api/test \
  -H 'x-authorization: api-key-here'

```

You might also want to attach this middleware to your `api` middleware group in your `app/Http/Kernel.php` to take advantage of other Laravel features such as throttling.

```
/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    ...

    'api' => [
        'throttle:60,1',
        'bindings',
        'auth.apikey',
    ],
];
```

If you noticed in the basic example, you can also access the attached model to the API key by calling `$request->user()`. We are attaching the related model in this method because in most use cases, this is actually the user.

### Unauthorized Requests

[](#unauthorized-requests)

Unauthorized requests will get a `401` status response with the following JSON:

```
{
  "error": {
    "code": "401",
    "http_code": "GEN-UNAUTHORIZED",
    "message": "Unauthorized."
  }
}
```

### ApiGuardController

[](#apiguardcontroller)

The `ApiGuardController` takes advantage of [Fractal](http://fractal.thephpleague.com/) and [api-response](https://github.com/ellipsesynergie/api-response) libraries.

This enables us to easily create APIs with models and use transformers to give a standardized JSON response.

Here is an example:

Let's say you have the following model:

```
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $fillable = [
        'name',
    ];
}
```

You can make a basic controller which will return all books like this:

```
use Chrisbjr\ApiGuard\Http\Controllers\ApiGuardController;
use App\Transformers\BookTransformer;
use App\Book;

class BooksController extends ApiGuardController
{
    public function all()
    {
        $books = Book::all();

        return $this->response->withCollection($books, new BookTransformer);
    }
}
```

Now, you'll need to make the transformer for your Book object. Transformers help with defining and manipulating the variables you want to return to your JSON response.

```
use League\Fractal\TransformerAbstract;
use App\Book;

class BookTransformer extends TransformerAbstract
{
    public function transform(Book $book)
    {
        return [
            'id'         => $book->id,
            'name'       => $book->name,
            'created_at' => $book->created_at,
            'updated_at' => $book->updated_at,
        ];
    }
}
```

Once you have this accessible in your routes, you will get the following response from the controller:

```
{
  "data": {
    "id": 1,
    "title": "The Great Adventures of Chris",
    "created_at": {
      "date": "2017-05-25 18:54:18",
      "timezone_type": 3,
      "timezone": "UTC"
    },
    "updated_at": {
      "date": "2017-05-25 18:54:18",
      "timezone_type": 3,
      "timezone": "UTC"
    }
  }
}
```

More examples can be found on the Github page: .

To learn more about transformers, visit the PHP League's documentation on Fractal: [Fractal](http://fractal.thephpleague.com/)

### API Validation Responses

[](#api-validation-responses)

ApiGuard comes with a request class that can handle validation of requests for you and throw a standard response.

You can create a `Request` class as you usually do but in order to get a standard JSON response you'll have to extend the `ApiGuardFormRequest` class.

```
use Chrisbjr\ApiGuard\Http\Requests\ApiGuardFormRequest;

class BookStoreRequest extends ApiGuardFormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required',
        ];
    }
}
```

Now you can use this in your controller as you normally do with Laravel:

```
use Chrisbjr\ApiGuard\Http\Controllers\ApiGuardController;
use App\Transformers\BookTransformer;
use App\Book;

class BooksController extends ApiGuardController
{
    public function store(BookStoreRequest $request)
    {
        // Request should already be validated

        $book = Book::create($request->all())

        return $this->response->withItem($book, new BookTransformer);
    }
}
```

If the request failed to pass the validation rules, it will return with a response like the following:

```
{
  "error": {
    "code": "GEN-UNPROCESSABLE",
    "http_code": 422,
    "message": {
      "name": [
        "The name field is required."
      ]
    }
  }
}
```

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community20

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 64.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~36 days

Recently: every ~92 days

Total

28

Last Release

3421d ago

Major Versions

v0.7 → v1.02015-03-27

v1.0 → v2.0.02015-03-27

v1.1 → v2.2.12015-05-03

v1.1.3 → v2.2.22015-06-16

v2.3.0 → v3.0.02016-02-01

PHP version history (2 changes)v0.1PHP &gt;=5.4.0

v3.1.0PHP &gt;=5.5.9

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/5157609?v=4)[Tim Joosten](/maintainers/Tjoosten)[@Tjoosten](https://github.com/Tjoosten)

---

Top Contributors

[![chrisbjr](https://avatars.githubusercontent.com/u/571279?v=4)](https://github.com/chrisbjr "chrisbjr (120 commits)")[![awkwardusername](https://avatars.githubusercontent.com/u/2331465?v=4)](https://github.com/awkwardusername "awkwardusername (41 commits)")[![rchoffardet](https://avatars.githubusercontent.com/u/5098668?v=4)](https://github.com/rchoffardet "rchoffardet (3 commits)")[![Schnoop](https://avatars.githubusercontent.com/u/1263407?v=4)](https://github.com/Schnoop "Schnoop (3 commits)")[![gholol](https://avatars.githubusercontent.com/u/7087411?v=4)](https://github.com/gholol "gholol (2 commits)")[![jotafurtado](https://avatars.githubusercontent.com/u/748350?v=4)](https://github.com/jotafurtado "jotafurtado (2 commits)")[![ethanhann](https://avatars.githubusercontent.com/u/402597?v=4)](https://github.com/ethanhann "ethanhann (1 commits)")[![gitter-badger](https://avatars.githubusercontent.com/u/8518239?v=4)](https://github.com/gitter-badger "gitter-badger (1 commits)")[![jeroenlammerts](https://avatars.githubusercontent.com/u/4282711?v=4)](https://github.com/jeroenlammerts "jeroenlammerts (1 commits)")[![JoeOBrien](https://avatars.githubusercontent.com/u/5874388?v=4)](https://github.com/JoeOBrien "JoeOBrien (1 commits)")[![jwdeitch](https://avatars.githubusercontent.com/u/7282720?v=4)](https://github.com/jwdeitch "jwdeitch (1 commits)")[![snipe](https://avatars.githubusercontent.com/u/197404?v=4)](https://github.com/snipe "snipe (1 commits)")[![Tjoosten](https://avatars.githubusercontent.com/u/5157609?v=4)](https://github.com/Tjoosten "Tjoosten (1 commits)")[![vikkio88](https://avatars.githubusercontent.com/u/248805?v=4)](https://github.com/vikkio88 "vikkio88 (1 commits)")[![alexgignac](https://avatars.githubusercontent.com/u/1719308?v=4)](https://github.com/alexgignac "alexgignac (1 commits)")[![vinicius73](https://avatars.githubusercontent.com/u/1561347?v=4)](https://github.com/vinicius73 "vinicius73 (1 commits)")[![andrewklau](https://avatars.githubusercontent.com/u/2239920?v=4)](https://github.com/andrewklau "andrewklau (1 commits)")[![awalko](https://avatars.githubusercontent.com/u/8527055?v=4)](https://github.com/awalko "awalko (1 commits)")[![cernicc](https://avatars.githubusercontent.com/u/6370441?v=4)](https://github.com/cernicc "cernicc (1 commits)")[![clrke](https://avatars.githubusercontent.com/u/7193634?v=4)](https://github.com/clrke "clrke (1 commits)")

---

Tags

jsonapilaravelrestapi keysapi authentication

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/sijot-api-guard/health.svg)

```
[![Health](https://phpackages.com/badges/sijot-api-guard/health.svg)](https://phpackages.com/packages/sijot-api-guard)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k15.1M129](/packages/laravel-pulse)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M127](/packages/roots-acorn)[api-platform/laravel

API Platform support for Laravel

59156.3k11](/packages/api-platform-laravel)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45444.2k1](/packages/pressbooks-pressbooks)[alajusticia/laravel-logins

Session management in Laravel apps, user notifications on new access, support for multiple separate remember tokens, IP geolocation, User-Agent parser

2014.5k](/packages/alajusticia-laravel-logins)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
