PHPackages                             phpsa/laravel-api-controller - 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. [API Development](/categories/api)
4. /
5. phpsa/laravel-api-controller

ActiveLibrary[API Development](/categories/api)

phpsa/laravel-api-controller
============================

A laravel api base controller with basic CRUD mapped to the model

v7.4.0(1y ago)4860.6k↓22.9%19[2 issues](https://github.com/phpsa/laravel-api-controller/issues)[1 PRs](https://github.com/phpsa/laravel-api-controller/pulls)4MITPHPPHP ^8.1CI failing

Since May 31Pushed 1y ago4 watchersCompare

[ Source](https://github.com/phpsa/laravel-api-controller)[ Packagist](https://packagist.org/packages/phpsa/laravel-api-controller)[ GitHub Sponsors](https://github.com/phpsa)[ RSS](/packages/phpsa-laravel-api-controller/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (7)Versions (221)Used By (4)

Laravel Api Controller
======================

[](#laravel-api-controller)

\[\[*TOC*\]\]

[![For Laravel 9 to 10](https://camo.githubusercontent.com/4f43ab6c221fb4607f6f8245241f99f78ed42ca3902c3cfe3b05de328fea54e3/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d382e37253230746f253230392d626c75652e737667)](https://github.com/phpsa/laravel-api-controller/issues)[![Build Status](https://camo.githubusercontent.com/5a85e1ee7ad4a44cc95151f9bd406b59bddc00220bebfb9a6cf8da80b1b02867/68747470733a2f2f6170692e7472617669732d63692e636f6d2f70687073612f6c61726176656c2d6170692d636f6e74726f6c6c65722e7376673f6272616e63683d6d6173746572)](https://travis-ci.com/phpsa/laravel-api-controller)[![Coverage Status](https://camo.githubusercontent.com/405243c48aa260e2212659e214ca6fcf17b0e5d13f1b1e0c53b8766eca1b104a/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f70687073612f6c61726176656c2d6170692d636f6e74726f6c6c65722f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/phpsa/laravel-api-controller?branch=master)[![Packagist](https://camo.githubusercontent.com/fdecd51f98f2c7416650df2212c564b056551e4c5370ca2c9a1bcabbf50256d1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f70687073612f6c61726176656c2d6170692d636f6e74726f6c6c65722e737667)](https://packagist.org/packages/phpsa/laravel-api-controller)[![Packagist](https://camo.githubusercontent.com/16618e9bc350861abfab05540809e048866fbc3d0c53439b8121f86d29bf61ae/68747470733a2f2f706f7365722e707567782e6f72672f70687073612f6c61726176656c2d6170692d636f6e74726f6c6c65722f642f746f74616c2e737667)](https://packagist.org/packages/phpsa/laravel-api-controller)[![Packagist](https://camo.githubusercontent.com/d03422abccaad97a47ede7d20e709a05b7775b6b517af72e8f898e0c20d9bfa7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f70687073612f6c61726176656c2d6170692d636f6e74726f6c6c65722e737667)](https://packagist.org/packages/phpsa/laravel-api-controller)[![Github Issues](https://camo.githubusercontent.com/ac099f18c1f54f393cd840c6df67f4a7df631d4d0824d0e0ea77b491e3817785/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f70687073612f6c61726176656c2d6170692d636f6e74726f6c6c6572)](https://github.com/phpsa/laravel-api-controller/issue)

Basic CRUD API Methods that can be extended for your models by default has a list, show, update, add and delete endpoint to interact with your model.

Installation
------------

[](#installation)

Install via composer

```
composer require phpsa/laravel-api-controller
```

### Publish Configuration File (optional - if you need to change any of the default configurations)

[](#publish-configuration-file-optional---if-you-need-to-change-any-of-the-default-configurations)

```
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
```

Usage
-----

[](#usage)

**CLI Commands**

- `artisan make:api:controller {ControllerName}` to generate the controller
- `artisan make:api:policy {PolicyName} -m {Model}` to generate a policy file
- `artisan make:api:resource {ResourceName|CollectionName}` to geneate the response resource

This will create a Api/ModelNameController for you and you will have the basic routes in place as follows:

- GET `api/v1/{model_name}` - list all/paged/filtered (class::index)
- GET `api/v1/{model_name}/$id` - Show a specified id (class::show)
- POST `api/v1/{model_name}` - Insert a new record (class::store)
- PUT `api/v1/{model_name}/$id` - Replace an existing record (class::update)
- PATCH `api/v1/{model_name}/$id` - Update an existing record (class::update)
- DELETE `api/v1/{model_name}/$id` - Delete an existing record (class::destroy)

If you specify `--soft-deletes` option on `make:api:controller` it will also create an additional `restore` controller endpoint &amp; route:

- PATCH `api/v1/{model_name}/$id` - Restore a soft-deleted record (class::restore). This only works for models with Soft Deletes enabled.

You can override the methods by simply putting in your own methods to override - method names in braces above

Events
------

[](#events)

- POST (class::store) - triggers a new `Phpsa\LaravelApiController\Events\Created` Event which has the new record available as `$record`
- PUT (class::update) - triggers a new `Phpsa\LaravelApiController\Events\Updated` Event which has the updated record available as `$record`
- DELETE (class::destroy) - triggers a new `Phpsa\LaravelApiController\Events\Deleted` Event which has the deleted record available as `$record`

Policies
--------

[](#policies)

Policies:

Generate with `php artisan make:policy PostPolicy --model=Post`

- Get list - calls the `viewAny` policy
- Get single - calls the `view` policy
- Post New - calls the `create` policy
- Put Update - calls the `update` policy
- Delete item - calls the `delete` policy

Query/Data modifiers in policies for the api endpoints

- `qualifyCollectionQueryWithUser($user, $repository)` -&gt; return void - add any queries to the repository (ie -&gt;where('x','))
- `qualifyItemQueryWithUser($user, $repository)`-&gt; return void - add any queries to the repository (ie -&gt;where('x','))
- `qualifyStoreDataWithUser($data)` - return the updated data array
- `qualifyUpdateDataWithUser($data)` - return the updated data array

Resources / Collections (Transforming)
--------------------------------------

[](#resources--collections-transforming)

Resources:

Generate with `php artisan make:apiresource UserResource` and `php artisan make:api:resource UserCollection`

Change the Resource to extend from:

use `Phpsa\LaravelApiController\Http\Resources\ApiResource` for your resource use `Phpsa\LaravelApiController\Http\Resources\ApiCollection` for your resource collection

in your controller override the following params:

```
	protected $resourceSingle = UserResource::class;
	protected $resourceCollection = UserCollection::class;
```

Snake vs Camel
--------------

[](#snake-vs-camel)

- middleware to convert all camel to snake: `Phpsa\LaravelApiController\Http\Middleware\SnakeCaseInputs`
- set request header `X-Accept-Case-Type` to either `snake` or `camel` to alter your data response

Filtering
---------

[](#filtering)

### stable option that will be removed once experimental stable

[](#stable-option-that-will-be-removed-once-experimental-stable)

For the get command you can filter by using the following url patterns

SeperatorDescriptionExampleResult*`=`*Equals?filter\[field\]=helloselect ... where field = 'hello'*`!=`*Not Equals?filter\[field!\]=helloselect ... where field != 'hello'*``*Not Equals (alt)?filter\[field&lt;&gt;\]=helloselect ... where field != 'hello'*`>`*Greater Than?filter\[field&gt;\]=5select ... where field &gt; 5*`>=`*Greater Or Equal to?filter\[field&gt;=\]=5select ... where field &gt;= 5*`whereNotNull('age');
}
```

Add to your allowedScopes and can then be called in url as `?ageNull=1` for where null and `?ageNull=0` for where age not null

### Filtering

[](#filtering-1)

- use the url pattern `filters[column][operator]=value` eg `filters[age][>]=18&filters[title][contains]=testing`

SeperatorDescriptionExampleResultempty / *`=`* / `is` / `equals`Equals?filters\[field\]=hello / ?filters\[field\]\[is\]=helloselect ... where field = 'hello'*`!=`* / `!is` / `!equals` / `not_equals`Not Equals?filters\[field\]\[!is\]=helloselect ... where field != 'hello'*`>`* / `greater_than`Greater Than?filters\[field\]\[greater\_than\]=5select ... where field &gt; 5*`>=`* / `greater_than_or_equal_to` / `greater_or_equal` / `gte`Greater Or Equal to?filters\[field\]\[greater\_or\_equal\]=5select ... where field &gt;= 5*`model())->newQuery();
    }

```

method in your controller to include any additional queries / scopes etc.

Requests
--------

[](#requests)

We have added a request macro to enable you to set these on your request as needed:

eg:

```
    public function index(Request $request)
    {

        $request->apiFilter('user_id', auth()->id());
        $request->apiFilter('owner_id', 'not_equals', auth()->id());
        $request->apiFilter('age', '>=', 5);
        $request->apiFilter('age', ']=900&filter_by_relation_group[b][name]=color&filter_by_relation_group[b][value]=color`

```
 public function scopeFilterByRelationGroup(Builder $builder, array $wheres): void
    {
        $where =  collect($wheres)->map(fn ($child) =>
           $this->parseFiltersArray($child)
        )->each(
            fn($group, $key) => $builder->whereHas('Relation', function ($subQ) use ($group, $key) {
                $group->each(
                    fn($filter, $column) => collect($filter)->each(fn($value, $comparison) => $this->buildQuery($column, $comparison, $value, $subQ))
                );
            }
            )
        );

    }

```

Fields, Relationships, Sorting &amp; Pagination
===============================================

[](#fields-relationships-sorting--pagination)

Fields
------

[](#fields)

By default all fields are returned, you can limit that to specific fields in the following ways:

- Api Controller parameter `$defaultFields` default as `protected $defaultFields = ['*'];` - switch to include an array of fields
- fields param in url querystring: ie `fields=id,name,age` = will only return those, this will also override the above.
- in your response resource you can set the static::allowedFields to lock down which fields are returnable.
    - This also controls which related resources are returnable. Include the key that is used in `$mapResources` (see "Relationships" below).
- `addfields` and `removefields` params in url querystring will work with these.
- Use laravel [eloquent model `$appends`](https://laravel.com/docs/6.x/eloquent-serialization#appending-values-to-json) property to automatically include custom attribute accessors.

### Gated Response Fields

[](#gated-response-fields)

Gates can be used to control access to fields and related resources, by defining `$gatedFields`:

```
protected static array $fieldGates = [
    'gate-one' => [
        'fieldA',
        'fieldB',
     ],
     'gate-two' => [
       'fieldA',
       'fieldC,
       'relatedResourceD'
     ]
];

```

Each specified gate will be used to determine whether that set of fields will be included.

Each gate will be passed the resource as well as the user, so it can test whether the user should be allowed to access that specific resource.

Example gate definition:

```
  Gate::define(
      'supervises-the-group',
      fn ($user, Group $group) => (int) $user->id === $group->supervisor_id
  );

```

Relationships
-------------

[](#relationships)

- Using the relationships defined in your models, you can pass a comma delimited list eg `include=join1,join2` which will return those joins (one or many).

Simply add a `protected static $mapResources` to your `Resource` to define which resources to assign your related data. E.e., for a one to many relationship, you should specify a collection, and a one-to-one relationship specify the related resource directly. This will allow the API to properly format the related record.

```
    protected static $mapResources = [
        'notes' => NotesCollection::class,
        'owner' => OwnerResource::class
    ];

```

- You can automatically update and create related records for most types of relationships. Just include the related resource name in your POST or PUT request.
- Important: if you are using `$defaultFields` and/or `$allowedFields` in your resource, the related resource key from `$mapResources` must also be included in those lists for that related resource to be included.

For `BelongsToMany` or `MorphToMany` relationships, you can choose the sync strategy. By default, this will take an *additive* strategy. That is to say, related records sent will be ADDED to any existing related records. On a request-by-request basis, you can opt for a *sync* strategy which will remove the pivot for any related records not listed in the request. Note the actual related record will not be removed, just the pivot entry.

To opt for the *sync* behavaiour, set `?sync[field]=true` in your request.

Sorting
-------

[](#sorting)

- Sorts can be passed as comma list aswell, ie `sort=age asc` or `sort=age asc,name desc,eyes` - generates sql of `sort age asc` and `sort age asc, name desc, eyes asc` respectively
- Default sort can also be added on the controller using by overrideing the `protected $defaultSort = null;` parameter

Pagination
----------

[](#pagination)

- pagination can be enabled/disbled on the controller by overriding the `protected $defaultLimit = 25;` on the controller
- pagination can also be passed via the url using `limit=xx&page=y`
- pagination can also be limited to a max per page by overriding the `protected $maximumLimit = false;` parameter

Validation
----------

[](#validation)

- When Posting a new record, validation can be done by adding a `rulesForCreate` method to your controller returning an array eg

```
[
    'email' => 'required|email',
    'games' => 'required|numeric',
]
```

see

- for updating a record, add a method `rulesForUpdate` per above.

Defaults
--------

[](#defaults)

The following parameters are set in the Base Api controller and can be overwritten by your Controller on a case by case basis:

- `protected $resourceSingle = JsonResource::class;` Collection to use for your single resource
- `protected $resourceCollection = ResourceCollection::class;` Collection to use for your resource collection
- `protected $defaultFields = ['*'];` Default Fields to respond with
- `protected $defaultSort = null;` Set the default sorting for queries.
- `protected $defaultLimit = 25;` Number of items displayed at once if not specified. (0 = maximumLimit)
- `protected $maximumLimit = 0;` Maximum limit that can be set via $\_GET\['limit'\]. - this ties in with the defaultLimit aswell, and if wanting to disable pagination , both should be 0. ) will allow all records to be returned in a single call.
- `protected $unguard = false;` Do we need to unguard the model before create/update?

Scopes
------

[](#scopes-1)

### SoftDeleted Records

[](#softdeleted-records)

add the `Phpsa\LaravelApiController\Model\Scopes\WithSoftDeletes` trait to your model, add to your resource file:

```
class MyModelResource extends ApiResource
{

 protected static $allowedScopes = [
        'withTrashed',
        'onlyTrashed'
    ];
```

you can now append `withTrashed=1` or `onlyTrashed=1` to your query.

Responses
---------

[](#responses)

you can override responses for each point by overriding the following protected methods:

- handleIndexResponse
- handleStoreResponse
- handleShowResponse
- handleUpdateResponse
- handleDestroyResponse

Perforance Tips
---------------

[](#perforance-tips)

### Cache Table column definitions

[](#cache-table-column-definitions)

\-- introduced add the ability to cache the table definitions to reduce calls to fetch table columns, to enable either enable in the config file or set the `PHPSA_API_CACHE_TABLE_COLUMNS` variable to true.

### Raw Pagination gets

[](#raw-pagination-gets)

\-- handleIndexAction will use full eloquent models, handleIndexActionRaw will bypass eloquent and use raw responses from the database.

Scramble Intergration
---------------------

[](#scramble-intergration)

in your scramble config file add `\]hpsa\LaravelApiController\Scramble\ApiResourceOpenApi::class` to the extensions array. this will enhance the documentation for apiResources.

Security
--------

[](#security)

If you discover any security related issues, please email instead of using the issue tracker.

Credits
-------

[](#credits)

- [Craig G Smith](https://github.com/phpsa)
- [Sam Sehnert](https://github.com/samatcd)
- [Phil Taylor](https://github.com/codeberry)
- [All contributors](https://github.com/phpsa/laravel-api-controller/graphs/contributors)

Sponsors
--------

[](#sponsors)

- [Custom D](https://customd.com)

###  Health Score

56

—

FairBetter than 98% of packages

Maintenance46

Moderate activity, may be stable

Popularity45

Moderate usage in the ecosystem

Community30

Small or concentrated contributor base

Maturity87

Battle-tested with a long release history

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~11 days

Recently: every ~73 days

Total

184

Last Release

462d ago

Major Versions

v4.3.0 → 5.0.0-alpha.12022-06-01

v5.9.5 → V6.0.02023-03-12

v5.9.6 → V6.1.02023-03-28

v6.1.1 → v7.0.02023-07-26

6.x-dev → v7.1.02023-10-31

PHP version history (6 changes)0.1.0PHP &gt;=7.0

0.1.1PHP &gt;=7.1.3

1.2.0PHP &gt;=7.2

2.0.0-b.3PHP ^7.3|^8.0

v3.1.0PHP ^8.0

5.x-devPHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/bbe4c97ef26aca9d6792775ea44a4c83215881b158f2d3894279c7b73bedda3c?d=identicon)[phpsa](/maintainers/phpsa)

---

Top Contributors

[![craigAtCD](https://avatars.githubusercontent.com/u/152445143?v=4)](https://github.com/craigAtCD "craigAtCD (157 commits)")[![phpsa](https://avatars.githubusercontent.com/u/952595?v=4)](https://github.com/phpsa "phpsa (92 commits)")[![semantic-release-bot](https://avatars.githubusercontent.com/u/32174276?v=4)](https://github.com/semantic-release-bot "semantic-release-bot (44 commits)")[![samatcd](https://avatars.githubusercontent.com/u/1476991?v=4)](https://github.com/samatcd "samatcd (15 commits)")[![Cadienvan](https://avatars.githubusercontent.com/u/5492927?v=4)](https://github.com/Cadienvan "Cadienvan (5 commits)")[![joshatcd](https://avatars.githubusercontent.com/u/141605602?v=4)](https://github.com/joshatcd "joshatcd (4 commits)")[![robertatcd](https://avatars.githubusercontent.com/u/1477106?v=4)](https://github.com/robertatcd "robertatcd (3 commits)")[![timack](https://avatars.githubusercontent.com/u/1098068?v=4)](https://github.com/timack "timack (2 commits)")[![janeatcd](https://avatars.githubusercontent.com/u/130412527?v=4)](https://github.com/janeatcd "janeatcd (2 commits)")[![PellegrinoDurante](https://avatars.githubusercontent.com/u/10448632?v=4)](https://github.com/PellegrinoDurante "PellegrinoDurante (2 commits)")[![JituSSingh](https://avatars.githubusercontent.com/u/77375648?v=4)](https://github.com/JituSSingh "JituSSingh (1 commits)")[![Hambrook](https://avatars.githubusercontent.com/u/581935?v=4)](https://github.com/Hambrook "Hambrook (1 commits)")[![SnirCD](https://avatars.githubusercontent.com/u/79120468?v=4)](https://github.com/SnirCD "SnirCD (1 commits)")[![benfreke](https://avatars.githubusercontent.com/u/2102440?v=4)](https://github.com/benfreke "benfreke (1 commits)")

---

Tags

apilaravelrest-apiapilaravelcontroller

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

### Embed Badge

![Health badge](/badges/phpsa-laravel-api-controller/health.svg)

```
[![Health](https://phpackages.com/badges/phpsa-laravel-api-controller/health.svg)](https://phpackages.com/packages/phpsa-laravel-api-controller)
```

###  Alternatives

[darkaonline/l5-swagger

OpenApi or Swagger integration to Laravel

2.9k34.0M112](/packages/darkaonline-l5-swagger)[knuckleswtf/scribe

Generate API documentation for humans from your Laravel codebase.✍

2.3k12.2M45](/packages/knuckleswtf-scribe)[nickurt/laravel-postcodeapi

Universal PostcodeApi for Laravel 11.x/12.x/13.x

97221.2k](/packages/nickurt-laravel-postcodeapi)[mozex/anthropic-laravel

Anthropic PHP for Laravel is a supercharged PHP API client that allows you to interact with the Anthropic API

71226.4k1](/packages/mozex-anthropic-laravel)[d-scribe/laraquick

A collection of classes to be extended/used in laravel applications for quick development

371.8k1](/packages/d-scribe-laraquick)

PHPackages © 2026

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