Download the PHP package rakhavirgiandi/laravel-apigator without Composer
On this page you can find all versions of the php package rakhavirgiandi/laravel-apigator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download rakhavirgiandi/laravel-apigator
More information about rakhavirgiandi/laravel-apigator
Files in rakhavirgiandi/laravel-apigator
Package laravel-apigator
Short Description Laravel package to auto-generate CRUD API (Controller, Model, Routes) from database tables
License MIT
Informations about the package laravel-apigator
Laravel Apigator
Auto-generate production-ready CRUD APIs from your database tables β in seconds.
Laravel Apigator is a developer-experience-first package that reads your existing database schema and generates a full, working CRUD API stack: Model, Service, Controller, and Routes β all wired together and ready to use. No more boilerplate. No more copy-paste. Just run one command and your API is live.
It also ships with a powerful runtime query engine that gives every generated endpoint free filtering, sorting, full-text search, pagination, eager loading, and DataTables server-side support β all through query parameters, with zero extra code.
π Table of Contents
- Features β¨
- Requirements π
- Installation π¦
- Configuration βοΈ
- Quick Start π
- The Generate Command π οΈ
- Generating a Single Table
- Generating All Tables
- Selective Generation
- Custom Directories
- Multi-Database Connections
- Force Overwrite
- Generated Files π
- Model
- Service
- Controller
- Routes
- Runtime Query API π
- Filtering
- Sorting
- Pagination
- Full-Text Search
- OR Groups
- Eager Loading (Relations)
- Schema Customization (
mapSchema) πΊοΈ- Defining Fields
- Adding JOINs
- Static WHERE Conditions
- Raw SQL Expressions
- DataTables Integration π
- Model Revamping π
- Exception Handling π¨
- Traits Reference π§©
- Configuration Reference ποΈ
- License π
Features β¨
- One-command API generation β generates Model, Service, Controller, and Routes from any database table
- Generate all tables at once with
--table=all, auto-skipping system tables - Selective generation β only generate what you need (
model,service,controller,route) - Smart validation rules β auto-derived from column types with name-based heuristics (email, phone, uuid, slug, url, coordinates, and more)
- Automatic type casting β
$castspopulated from database column types - Soft Delete detection β automatically adds
SoftDeletestrait when adeleted_atcolumn is present - Rich runtime query API β filter, sort, search, and paginate any endpoint with query parameters
- 16 filter operators β from
eq/neqtobetween,in,like,null,date_from, and more - Eager loading β load Eloquent relations on-the-fly via
?with=relation1,relation2.nested - DataTables server-side β every generated controller includes a
/resource_datatableendpoint - Schema customization β define custom
SELECTcolumns,JOINs, and staticWHEREconditions viamapSchema() - Model Revamping β surgically update an existing model's casts, rules, and schema when your table changes
- Multi-database connection support β target any configured database connection
- SQL injection safe β all column names are whitelisted and sanitized
- OpenAPI annotations β controller methods pre-annotated for Swagger/L5-Swagger
Requirements π
| Dependency | Version |
|---|---|
| PHP | ^8.1 |
| Laravel | ^10.0, ^11.0, or ^12.0 |
Supported databases: MySQL, MariaDB, PostgreSQL, SQLite, SQL Server.
Installation π¦
Install the package via Composer:
Laravel's auto-discovery will register the service provider automatically. No manual registration is required.
Optionally, publish the configuration file:
This creates config/apigator.php in your project, which you can customize to your liking.
Configuration βοΈ
After publishing, open config/apigator.php:
All settings can also be overridden at runtime via command-line options (see Command Reference).
Quick Start π
Suppose you have a products table. Run:
That's it. Apigator will create:
Your API is now fully functional:
| Method | Endpoint | Action |
|---|---|---|
GET |
/products |
Paginated list |
GET |
/products/{id} |
Single record |
POST |
/products |
Create |
PATCH |
/products/{id} |
Update |
DELETE |
/products/{id} |
Delete |
POST |
/products_datatable |
DataTables server-side |
The Generate Command π οΈ
Generating a Single Table
Generates Order, OrderService, OrderController, and appends routes for the orders table.
Generating All Tables
Iterates every table in the database, skipping the ones listed in exclude_tables. Reports generated vs. skipped at the end.
Selective Generation
Use --generate to control which components are created. Accepts a comma-separated list of: model, service, controller, route.
Note: The generator respects dependency order. Generating a
controllerrequires theservicefile to already exist, and generating aservicerequires themodelto exist.
Custom Directories
Override the default output paths on a per-run basis:
Namespaces are derived automatically from the directory path (e.g. Domain/Users/Models β App\Domain\Users\Models).
Multi-Database Connections
Target any connection defined in config/database.php:
When a non-default connection is specified, the generated model will include a $connection property set to that connection name.
Force Overwrite
By default, Apigator will not overwrite existing files. Add --force to regenerate:
β οΈ This will completely replace existing model, service, and controller files. Any manual customizations will be lost. Consider using
--revamp-tableto update only specific sections of an existing model.
Generated Files π
Model is a fully-featured Eloquent model with:
$fillable β automatically populated with all non-system columns (id, created_at, updated_at, deleted_at are excluded):
$casts β column types are mapped to appropriate PHP types:
| DB Type | PHP Cast |
|---|---|
int, bigint, integer |
integer |
tinyint |
boolean |
decimal, numeric |
decimal:2 |
float, double, real |
float |
json, jsonb |
array |
date |
date |
datetime, timestamp |
datetime |
| Everything else | string |
Validation rules β both createRules() (for POST) and updateRules() (for PATCH) are auto-generated with smart type + name-based heuristics. See the full Validation Rules table below.
mapSchema() β a customizable method that defines which columns to SELECT, any JOINs to apply, and static WHERE conditions. See Schema Customization.
Soft Deletes β if a deleted_at column is detected, the SoftDeletes trait is automatically imported and applied.
Validation Rules Reference
Beyond basic type rules, Apigator applies smart name-based heuristics:
| Column Name Pattern | Generated Rule |
|---|---|
Contains email |
string, email:rfc,dns |
Matches url, link, website, endpoint |
string, url |
Matches uuid, guid |
string, uuid |
Matches ip_address, ip_addr |
string, ip |
Matches phone, mobile, handphone, telp |
string, regex:/^+?[0-9\s\-().]{7,20}$/ |
Exactly password |
string, min:8 |
Exactly password_confirmation |
string, same:password |
Exactly slug or ends with _slug |
string, slug regex |
Matches username, user_name |
string, min:3, max:30, alphanumeric regex |
Matches color, colour |
string, hex color regex |
Matches lat, latitude |
numeric, between:-90,90 |
Matches lng, lon, longitude |
numeric, between:-180,180 |
Matches price, amount, qty, total, etc. |
numeric, min:0 |
Exactly age |
integer, min:0, max:150 |
Ends with _id |
integer, min:1 |
ENUM or SET column |
Rule::in([...values]) |
Service (app/Services/ProductService.php) provides a clean static API for all CRUD operations. It handles validation, database transactions, and error handling for you.
Every mutating method (createRecord, updateRecord, deleteRecord) runs inside a database transaction and throws an ApigatorException on failure, which Laravel's exception handler renders automatically as a clean JSON response.
Controller (app/Http/Controllers/API/ProductController.php) is a thin layer that delegates to the service and formats responses:
All methods include pre-written OpenAPI / Swagger annotations (@OA\Get, @OA\Post, etc.), ready to be picked up by tools like L5-Swagger.
Routes to your route file (default: routes/api.php) inside a clearly marked block:
The use ProductController; import statement is also injected automatically. Running the command a second time will not duplicate routes β Apigator checks for the marker and skips gracefully.
Runtime Query API π
Every generated endpoint supports a rich query API out of the box, driven entirely by request parameters. No extra code required.
Filtering
Append filter parameters as query strings. The default operator is eq (equality).
Use bracket notation to apply a specific operator:
Available operators:
| Operator | SQL Equivalent | Example |
|---|---|---|
eq (default) |
= value |
?status=active |
neq |
!= value |
?status[neq]=inactive |
gt |
> value |
?price[gt]=100 |
gte |
>= value |
?price[gte]=100 |
lt |
< value |
?stock[lt]=10 |
lte |
<= value |
?stock[lte]=50 |
like |
LIKE %value% |
?name[like]=apple |
starts |
LIKE value% |
?name[starts]=pro |
ends |
LIKE %value |
?name[ends]=plus |
in |
IN (a, b, c) |
?status[in]=active,pending |
not_in |
NOT IN (a, b, c) |
?status[not_in]=deleted |
null |
IS NULL |
?deleted_at[null]=1 |
not_null |
IS NOT NULL |
?published_at[not_null]=1 |
between |
BETWEEN a AND b |
?price[between]=10,100 |
date_from |
DATE(col) >= value |
?created_at[date_from]=2024-01-01 |
date_to |
DATE(col) <= value |
?created_at[date_to]=2024-12-31 |
Security: All column names are validated against a whitelist derived from your schema. Unknown or unallowed columns are silently ignored, preventing SQL injection.
Sorting
Use _sort to specify sort columns. Prefix with - for descending order. Chain multiple columns with commas.
Pagination
The response includes a meta object:
The per_page value is clamped between 1 and 1000. The default is controlled by default_per_page in the config.
Full-Text Search
Use _search to perform a LIKE search across all string-type columns simultaneously:
This generates a WHERE (col1 LIKE '%wireless headphones%' OR col2 LIKE '%wireless headphones%' OR ...) query across every searchable text column defined in your schema.
OR Groups
Combine multiple conditions with OR logic using the _or parameter:
This generates:
You can mix multiple operators within each group:
Eager Loading (Relations)
Load Eloquent relations on-the-fly without modifying the controller:
Apigator validates each relation segment against the model before passing it to ->with(). Invalid or misspelled relations are silently dropped, so a client typo will never cause a 500 error.
Schema Customization (mapSchema) πΊοΈ
The mapSchema() method is the heart of Apigator's query engine. It lets you control exactly which columns are selected, which tables are joined, and which conditions are always applied β all without touching controller or service logic.
The generated version selects only the table's own columns, but you can freely extend it.
Defining Fields
Each entry in 'field' maps an alias to a column expression:
Field definition keys:
| Key | Description |
|---|---|
column |
The actual SQL column expression (table.column or raw SQL) |
alias |
The key name in the response JSON |
type |
string, int, float, bool, date, datetime, json |
is_raw |
Set to true to treat column as a raw SQL expression |
Searchable columns: Only
string-type fields are included in_searchfull-text queries. Settypeaccurately for correct behavior.
Adding JOINs
Extend the 'join' array to join related tables:
Then add the joined columns to 'field':
Supported join types: left, right, inner (default).
Static WHERE Conditions
Use 'where' to apply conditions that are always active, regardless of request parameters:
Raw SQL Expressions
Set is_raw => true to use any SQL expression as a column:
Dynamic Context in mapSchema
The $params arguments are passed in from the request, allowing you to build dynamic schemas:
DataTables Integration π
Every generated controller includes a datatable action that accepts a standard DataTables server-side POST payload:
The response follows the DataTables format:
The endpoint supports:
- Global search across all
searchable: truestring columns - Per-column search via the
columns[n].search.valuefield - Multi-column ordering via the
orderarray - All dynamic filter parameters from the Runtime Query API, appended alongside DataTables parameters
Model Revamping π
When your database schema changes (new columns added, types changed, columns removed), use --revamp-table to surgically update your existing model without losing any manual customizations:
The revamper only touches three sections of your model file:
| Section | What changes |
|---|---|
protected $fillable |
Rebuilt entirely from current DB columns |
protected $casts |
Rebuilt entirely from current DB column types |
createRules() return array |
Rebuilt from current DB columns |
updateRules() return array |
Rebuilt from current DB columns |
mapSchema() field entries |
Only own-table entries are replaced; custom entries from joined tables are preserved |
Everything else β your Eloquent relations, custom methods, joins, static wheres, and comments β is left completely untouched.
Example workflow for an evolving schema:
Exception Handling π¨
Apigator ships with two exception classes that integrate with Laravel's exception handler to return consistent JSON error responses automatically.
ApigatorException
A general-purpose HTTP exception. Laravel calls its render() method automatically, so you never need to manually catch it in controllers.
Named constructors for common scenarios:
JSON response shape:
ApigatorValidationException
Extends ApigatorException with field-level validation errors. Always returns HTTP 422.
JSON response shape:
Logging behavior:
ApigatorExceptiononly logs to your error tracker for5xxresponses.ApigatorValidationException(422) is never logged, keeping your logs clean from expected client errors.
Traits Reference π§©
ApiModelTrait
Mixed into every generated model. Provides the query engine that powers the runtime API.
| Method | Description |
|---|---|
buildBaseQuery(array $params) |
Builds the base Eloquent query by applying mapSchema(), dynamic filters, sorting, and eager loads |
applyEagerLoads(Builder $query, $instance, $with) |
Validates and applies ?with= relation chains |
applyDatatableSearch(Builder $query, array $params) |
Applies DataTables global and per-column search |
applyDatatableOrder(Builder $query, array $params) |
Applies DataTables column ordering |
You can call buildBaseQuery() directly in your own service methods if you need to build on top of the generated query:
ApiControllerTrait
Mixed into every generated controller. Provides standardized JSON response helpers.
Response shape for successResponse:
Configuration Reference ποΈ
| Key | Type | Default | Description |
|---|---|---|---|
controller_directory |
string |
Http/Controllers/API |
Controller output directory (relative to app/) |
model_directory |
string |
Models |
Model output directory (relative to app/) |
service_directory |
string |
Services |
Service output directory (relative to app/) |
route_delimiter |
string |
_ |
URL segment delimiter (_ β /my_resource, - β /my-resource) |
route_file |
string |
routes/api.php |
Route file where generated routes are appended |
default_per_page |
int |
10 |
Default pagination page size |
exclude_tables |
array |
(Laravel system tables) | Tables to skip during --table=all generation |
License π
This package is open-source software licensed under the MIT License.
Made with β€οΈ by Rakha R. Virgiandi
All versions of laravel-apigator with dependencies
illuminate/support Version ^10.0|^11.0|^12.0
illuminate/database Version ^10.0|^11.0|^12.0
illuminate/console Version ^10.0|^11.0|^12.0
illuminate/filesystem Version ^10.0|^11.0|^12.0