laravel-automatic-crud maintained by jgrygierek
Laravel Automatic CRUD
Automatic CRUD controllers with custom configurations for Laravel 12 and 13.
Table of Contents
Installation
composer require jgrygierek/laravel-automatic-crud
Laravel auto-discovers the service provider. Optionally publish the config file:
php artisan vendor:publish --tag=automatic-crud-config
Controllers
Creating a controller
Extend CrudableController and define a route resource. The controller resolves the model, form request, and resource classes by convention.
use JG\LaravelAutomaticCrud\Http\Controllers\CrudableController;
class ItemController extends CrudableController
{
//
}
// routes/api.php
Route::apiResource('items', ItemController::class);
Namespace override
Override getModelNamespace() in the controller to resolve the model from a different namespace without touching the config:
class ItemController extends CrudableController
{
protected function getModelNamespace(): string
{
return 'Domain\Inventory\Models';
}
}
Priority order (highest to lowest):
getModelNamespace()controller override- Custom configuration value
- Config default (
namespaces.model) - Hardcoded fallback (
App\Models)
Model class override
Override getModelClass() to bypass both the namespace method and the naming convention entirely:
class ItemController extends CrudableController
{
protected function getModelClass(): string
{
return Item::class;
}
}
Pagination and sorting
Pagination is enabled by default and returns 10 items per page wrapped in { data, links, meta }. Disable it to get a plain { data } array.
Sorting is triggered by ?sort_by=<field>. Direction defaults to asc when omitted or invalid. A non-string sort_by is ignored. Sorting is skipped when the query already has an orderBy (e.g.
applied inside modifyQuery()).
sort_by accepts any column name, including hidden ones, and an unknown column fails at the database level. Restrict it in the index request (see
Request class convention) to get a 422 instead. SortingRulesHelper::rules() returns the rules for both parameters:
use JG\LaravelAutomaticCrud\Helpers\SortingRulesHelper;
class IndexItemRequest extends FormRequest
{
public function rules(): array
{
return [
...SortingRulesHelper::rules(['name', 'created_at']),
'status' => ['sometimes', 'string'],
];
}
}
It allows sort_by only from the given columns and sort_direction only as asc or desc (case-sensitive).
Supported query parameters:
| Parameter | Values | Default | Description |
|---|---|---|---|
?pagination |
true, false |
true |
Enable or disable pagination |
?per_page |
integer | 10 |
Items per page (max 100) |
?sort_by |
column name | — | Column to sort by |
?sort_direction |
asc, desc |
asc |
Sort direction |
Override pagination defaults in the controller:
class ItemController extends CrudableController
{
protected function defaultIsPaginationEnabled(): bool
{
return false;
}
protected function defaultItemsPerPage(): int
{
return 25;
}
protected function maxItemsPerPage(): int
{
return 50;
}
protected function isPaginationOverrideAllowedInQuery(): bool
{
return false;
}
protected function isPerPageOverrideAllowedInQuery(): bool
{
return false;
}
}
Priority order (highest to lowest) for both pagination and per-page:
- Query parameter (
?pagination=,?per_page=) - Controller method override (
defaultIsPaginationEnabled(),defaultItemsPerPage()) - Config value (
pagination.paginate,pagination.per_page)
maxItemsPerPage() (config pagination.max_per_page) caps only ?per_page. The defaults above are not capped.
A ?pagination value that isn't a boolean or a ?per_page value that isn't an integer is ignored, so the defaults apply.
?pagination=false returns all items; disable it with pagination.allow_pagination_override to enforce the cap.
Pagination reads its query parameters from the resolved index request, so values set in its prepareForValidation() apply.
Customizing the query
Override modifyQuery() to apply additional constraints before pagination:
class ItemController extends CrudableController
{
protected function modifyQuery(Builder $query): Builder
{
return $query->where('active', true);
}
}
modifyQuery() is also applied when show, update, and destroy look up a record, so scoping such as multi-tenancy or ownership filters is enforced consistently everywhere, not just on index.
Looking up records by a custom key
show, update, and destroy look up the record by the model's route key (getRouteKeyName(), which falls back to the primary key by default). To look up by a different column on a specific route — without changing the model globally — use Laravel's route binding field syntax:
// routes/api.php
Route::get('orders/{order:uid}', [OrderController::class, 'show']);
Route::put('orders/{order:uid}', [OrderController::class, 'update']);
Route::delete('orders/{order:uid}', [OrderController::class, 'destroy']);
The controller keeps the usual show(int|string $id) signature — the uid segment is resolved automatically from the route definition. Routes without an explicit binding field keep using the model's route key.
In nested routes (e.g. users/{user}/posts/{post}) the record is identified by the last route parameter, so $id passed to findModel() is the {post} value. Parent parameters are not used to constrain the lookup — scope it in modifyQuery() if needed. When overriding an action, forward all arguments with parent::show(...func_get_args()) — parent::show($id) would pass only the parent value.
findModel() is protected, so it can be overridden entirely if the lookup logic above doesn't fit (e.g. querying across multiple tables).
Skipping global scopes
index, show, update, and destroy all apply any global scopes registered on the model. Override withoutGlobalScopes() to exclude specific global scopes across all four:
class OrderController extends CrudableController
{
protected function withoutGlobalScopes(): array
{
return [PublishedScope::class];
}
}
Applies uniformly everywhere the model is queried — there's no per-action opt-out. Defaults to [] (no scopes skipped).
Customizing persistence
store, update, and destroy delegate the actual write to createModel(), updateModel(), and deleteModel(). Override any of them to add side effects around the write, without duplicating the surrounding transaction, event dispatch, or response handling:
class OrderController extends CrudableController
{
protected function updateModel(Model $model, array $data): Model
{
if (array_key_exists('status', $data) && $model->status !== $data['status']) {
$model->tokens()->delete();
}
return parent::updateModel($model, $data);
}
}
If the change goes beyond the persistence step itself (e.g. it also affects which event fires or what's returned), override the whole action (store(), update(), destroy()) instead.
Filtering with SearchableInterface
Implement SearchableInterface on a model to enable pipeline-based filtering on the index endpoint:
use JG\LaravelAutomaticCrud\Http\Interfaces\SearchableInterface;
use Illuminate\Database\Eloquent\Model;
class Item extends Model implements SearchableInterface
{
public function searchFilters(): array
{
return [
ActiveFilter::class,
NameFilter::class,
];
}
}
Filter classes receive the query builder through a pipeline:
class ActiveFilter
{
public function handle(Builder $query, Closure $next): Builder
{
return $next($query->where('active', true));
}
}
Config-keyed filters
searchFilters() can also return a keyed array to provide different filter sets per named configuration. The key matches the controller's getConfigName(); default is used as a fallback when no matching key is found:
class Item extends Model implements SearchableInterface
{
public function searchFilters(): array
{
return [
'default' => [NameFilter::class],
'api' => [ActiveFilter::class, NameFilter::class],
];
}
}
A controller overriding getConfigName() to return 'api' will get [ActiveFilter::class, NameFilter::class], while all others fall back to [NameFilter::class].
Actions
CrudableController provides the actions registered by Route::apiResource(). Additional actions are opt-in via traits and need their own routes.
| Action | Method | Route | Response | Event | Source |
|---|---|---|---|---|---|
index |
GET |
/items |
200 collection |
— | CrudableController |
store |
POST |
/items |
201 resource |
Created |
CrudableController |
show |
GET |
/items/{item} |
200 resource |
— | CrudableController |
update |
PUT/PATCH |
/items/{item} |
200 resource |
Updated |
CrudableController |
destroy |
DELETE |
/items/{item} |
204 no content |
Deleted |
CrudableController |
upsert |
PUT |
/item |
200/201 resource |
Updated/Created |
UpsertTrait |
export |
GET |
/items/export |
200 CSV download |
— | ExportTrait |
Every action resolves its form request by convention (see Request class convention). store, update, destroy, and upsert run inside a database transaction on the model's connection.
Upsert
upsert() is not part of CrudableController — add it to a specific controller with UpsertTrait, then register a route for it manually (it's not part of Route::apiResource()). It is meant for singleton (1:1) resources, where the record is identified by its owner instead of its own ID, so the route has no ID parameter:
use JG\LaravelAutomaticCrud\Traits\UpsertTrait;
class ProfileController extends CrudableController
{
use UpsertTrait;
protected function getUpsertAttributes(): array
{
return ['user_id' => auth()->id()];
}
}
// routes/api.php
Route::put('profile', [ProfileController::class, 'upsert']);
getUpsertAttributes() returns the attributes that identify the record (for a nested route such as users/{user}/profile, use ['user_id' => request()->route('user')]; return [] for a table holding a single record). The record is looked up by them within the controller's query (modifyQuery(), withoutGlobalScopes()). It responds 200 when it updated an existing record, 201 when it created one, and dispatches the matching Updated or Created event.
In a 1:N relation, return the parent together with a key that is unique within it, so the attributes still match exactly one record — the parent alone would always update the first matching record:
// Route::put('users/{user}/addresses/{type}', [AddressController::class, 'upsert']);
protected function getUpsertAttributes(): array
{
return [
'user_id' => request()->route('user'),
'type' => request()->route('type'),
];
}
The identifying attributes are set on the record directly: they don't need to be fillable and they take precedence over request values. If a matching record exists but is hidden from the controller's query (by modifyQuery(), a global scope, or soft deletion), upsert responds 404 instead of creating a duplicate. Override upsertModel(array $attributes, array $data): Model to customize the write.
Export
export() is not part of CrudableController — add it to a specific controller with ExportTrait, then register a route for it manually (before Route::apiResource(), so items/export isn't matched by show):
use JG\LaravelAutomaticCrud\Traits\ExportTrait;
class ItemController extends CrudableController
{
use ExportTrait;
}
// routes/api.php
Route::get('items/export', [ItemController::class, 'export']);
It streams a CSV download (items.csv, UTF-8, \r\n line endings per RFC 4180) of every matching record, built from the same query as index — SearchableInterface filters, modifyQuery(), withoutGlobalScopes(), and ?sort_by/?sort_direction all apply, but pagination doesn't.
Records are fetched from the database in chunks of export.chunk_size (5 000 by default) and appended to the same file, so memory usage stays flat regardless of the total. Unsorted queries are chunked by primary key (WHERE id > ?, via lazyById()), so every chunk is equally fast regardless of table size — existing where clauses are grouped first, so an ungrouped orWhere() in modifyQuery() or a filter can't bypass the key condition; sorted queries (?sort_by or an orderBy in modifyQuery()) are chunked by OFFSET, with the primary key appended to the sort order so chunks never skip or repeat records. If modifyQuery() joins other tables, select the model's columns explicitly (e.g. ->select('items.*')) — otherwise a joined table's id can overwrite the model's key and break chunking. An unsorted query on a model without a primary key can't be chunked and is read with a single query (cursor()), which skips eager loading. Override getExportChunkSize(): int in the controller to use a different chunk size for that controller. The first chunk is fetched before the response starts, so a failing query still returns an error status instead of an empty 200 download.
Each row is the model resolved to an array through {Model}ExportResource (see Resource class convention). Unlike the other resources it has no fallback: the class is checked on every export, even when nothing matches, and if it's missing a RuntimeException is thrown before the download starts, rather than silently exporting a shape built for the API. To export without one, override getResourceExportClass() (e.g. return JsonResource::class). The keys of the first row become the CSV header. Later rows are aligned to that header: missing keys are written as empty cells and keys not in the header are dropped. Booleans are written as 1/0, backed enums as their value, pure enums as their name, and other arrays and non-Stringable objects as JSON (invalid UTF-8 is replaced with U+FFFD and other unencodable values with 0 or null). When nothing matches, the file is empty.
Override getExportHeader(array $row): array to set the header yourself. By default it returns the keys of the first row (or [] when nothing matches, which leaves the file empty). Return a list of row keys (['id', 'name']), or a map of row keys to column labels (['id' => 'ID', 'name' => 'Name']). The header defines both the set and the order of exported columns: row values are written in header order, header keys missing from a row become empty cells, and row keys missing from the header are dropped. A non-empty header is written even when nothing matches.
Override getExportFileName(): string to change the file name, or getExportRow(Model $model, Request $request): array to build rows without a resource. The export resource is still required in that case, so also override getResourceExportClass() unless {Model}ExportResource exists:
class ItemController extends CrudableController
{
use ExportTrait;
protected function getResourceExportClass(): string
{
return JsonResource::class;
}
protected function getExportRow(Model $model, Request $request): array
{
return ['id' => $model->id, 'name' => $model->name];
}
}
Requests
Namespace override
Override getRequestNamespace() in the controller to resolve form requests from a different namespace without touching the config:
class ItemController extends CrudableController
{
protected function getRequestNamespace(): string
{
return 'Domain\Inventory\Requests';
}
}
Priority order (highest to lowest):
getRequestNamespace()controller override- Custom configuration value
- Config default (
namespaces.request) - Hardcoded fallback (
App\Http\Requests)
Request class convention
Given ItemController, the package looks for form request classes at:
| Action | Convention | Example |
|---|---|---|
| index | {request_namespace}\{Models}\Index{Model}Request |
App\Http\Requests\Items\IndexItemRequest |
| show | {request_namespace}\{Models}\Show{Model}Request |
App\Http\Requests\Items\ShowItemRequest |
| store | {request_namespace}\{Models}\Store{Model}Request |
App\Http\Requests\Items\StoreItemRequest |
| update | {request_namespace}\{Models}\Update{Model}Request |
App\Http\Requests\Items\UpdateItemRequest |
| upsert | {request_namespace}\{Models}\Upsert{Model}Request |
App\Http\Requests\Items\UpsertItemRequest |
| destroy | {request_namespace}\{Models}\Destroy{Model}Request |
App\Http\Requests\Items\DestroyItemRequest |
| export | {request_namespace}\{Models}\Export{Model}Request |
App\Http\Requests\Items\ExportItemRequest |
Form requests are optional by default — if the class does not exist, the standard request() is used.
For show, update, and destroy, the record is looked up via findModel() before the form request is resolved and validated, so a missing record always returns 404 regardless of the request body or authorization outcome.
Force custom requests
Set requests.force_custom to true to throw a RuntimeException when a request class is missing instead of silently falling back:
// config/automatic-crud.php
'requests' => [
'force_custom' => true,
],
Only validated fields
Set requests.only_validated to true (requires force_custom to also be true) to pass only $request->validated() fields to create() / update(), even
when the form request class is not a FormRequest:
// config/automatic-crud.php
'requests' => [
'force_custom' => true,
'only_validated' => true,
],
Reusing an already-resolved request
applyRequest() memoizes the resolved request for the current HTTP request (a controller instance reused for a later request resolves it again), so calling it more than once — directly and/or via getAllowedRequestValues()/validateRequest() — always returns the same instance instead of resolving (and re-validating) a new one. This makes it safe to resolve the request yourself for custom logic in a fully overridden action, and still use getAllowedRequestValues() afterwards:
class UserController extends CrudableController
{
public function update(int|string $id): JsonResource
{
$request = $this->applyRequest();
$user = $this->findModel($id);
$user->update($this->getAllowedRequestValues());
if ($request->has('role')) {
$user->syncRoles([$request->validated('role')]);
}
return $this->getResource($user);
}
}
Resources
Namespace override
Override getResourceNamespace() in the controller to resolve resources from a different namespace without touching the config:
class ItemController extends CrudableController
{
protected function getResourceNamespace(): string
{
return 'Domain\Inventory\Resources';
}
}
Priority order (highest to lowest):
getResourceNamespace()controller override- Custom configuration value
- Config default (
namespaces.resource) - Hardcoded fallback (
App\Http\Resources)
Resource class convention
Given ItemController, the package looks for resource classes at:
| Type | Used by | Convention | Example |
|---|---|---|---|
| Resource | show, store, update, upsert |
{resource_namespace}\{Model}Resource |
App\Http\Resources\ItemResource |
| Collection resource | index (applied to each record) |
{resource_namespace}\{Model}CollectionResource |
App\Http\Resources\ItemCollectionResource |
| Export resource | export (applied to each record) |
{resource_namespace}\{Model}ExportResource |
App\Http\Resources\ItemExportResource |
If {Model}Resource is not found, JsonResource is used as a fallback. If {Model}CollectionResource is not found, it falls back to {Model}Resource, then
JsonResource. {Model}ExportResource has no fallback — a RuntimeException is thrown when it's missing.
Resource class override
Override getResourceClass(), getResourceCollectionClass(), or getResourceExportClass() to bypass the namespace method and naming convention entirely:
class ItemController extends CrudableController
{
protected function getResourceClass(): string
{
return CustomItemResource::class;
}
protected function getResourceCollectionClass(): string
{
return CustomItemCollectionResource::class;
}
protected function getResourceExportClass(): string
{
return CustomItemExportResource::class;
}
}
Events
Namespace override
Override getEventNamespace() in the controller to resolve events from a different namespace without touching the config:
class ItemController extends CrudableController
{
protected function getEventNamespace(): string
{
return 'Domain\Inventory\Events';
}
}
Priority order (highest to lowest):
getEventNamespace()controller override- Custom configuration value
- Config default (
namespaces.event) - Hardcoded fallback (
App\Events)
Event class convention
Given ItemController, the package looks for event classes at:
| Action | Convention | Example |
|---|---|---|
| store | {event_namespace}\{Model}CreatedEvent |
App\Events\ItemCreatedEvent |
| update | {event_namespace}\{Model}UpdatedEvent |
App\Events\ItemUpdatedEvent |
| destroy | {event_namespace}\{Model}DeletedEvent |
App\Events\ItemDeletedEvent |
Events are optional — if the class does not exist, nothing is dispatched. When it exists, it's instantiated with the affected model and dispatched through Laravel's event dispatcher, deferred until the surrounding database transaction commits (via DB::afterCommit()) — it never fires if the transaction rolls back:
class ItemCreatedEvent
{
public function __construct(public readonly Model $model) {}
}
index, show, and export never dispatch events.
Event class override
Override getEvents() to control exactly which event class is dispatched for specific actions. It defaults to an empty array — any action not present as a key still falls back to the naming convention. An action mapped explicitly to null is disabled, bypassing the convention entirely:
class ItemController extends CrudableController
{
protected function getEvents(): array
{
return [
'Created' => CustomItemCreatedEvent::class,
'Deleted' => null,
];
}
}
In the example above, store dispatches CustomItemCreatedEvent instead of the convention class, destroy dispatches nothing, and update is untouched — it still resolves ItemUpdatedEvent by convention, since 'Updated' isn't a key in the array.
Unlike the convention (which silently skips a missing class), a class mapped explicitly in getEvents() must exist — a typo or a class that was renamed/removed throws a RuntimeException instead of silently dispatching nothing.
Configuration
// config/automatic-crud.php
return [
'configs' => [
'default' => [
'namespaces' => [
'model' => 'App\Models',
'resource' => 'App\Http\Resources',
'request' => 'App\Http\Requests',
'event' => 'App\Events',
],
'pagination' => [
'paginate' => true,
'per_page' => 10,
'max_per_page' => 100,
'allow_pagination_override' => true,
'allow_per_page_override' => true,
],
'requests' => [
'force_custom' => false,
'only_validated' => false,
],
'export' => [
'chunk_size' => 5000,
],
],
'api' => [
'pagination' => [
'per_page' => 25,
'allow_pagination_override' => false,
],
],
],
];
Custom configurations
A controller can select a named configuration to override default values:
class ItemController extends CrudableController
{
protected function getConfigName(): string
{
return 'api';
}
}
Config resolution order: named configuration value → default configuration value → hardcoded fallback.
Development
Without Docker
composer install
./vendor/bin/phpunit
./vendor/bin/pint
With Laravel Sail (Docker)
The Docker image is built from the Laravel Sail PHP 8.5 runtime. Composer must be installed locally first so the Sail runtime files are available as the build context.
composer install
Build and start the container:
./vendor/bin/sail build
./vendor/bin/sail up -d
Run tests and code style:
./vendor/bin/sail php vendor/bin/phpunit
./vendor/bin/sail php vendor/bin/pint
Open a shell inside the container:
./vendor/bin/sail shell
Stop the container:
./vendor/bin/sail down