Download the PHP package dev-toolbelt/laravel-eloquent-plus without Composer
On this page you can find all versions of the php package dev-toolbelt/laravel-eloquent-plus. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download dev-toolbelt/laravel-eloquent-plus
More information about dev-toolbelt/laravel-eloquent-plus
Files in dev-toolbelt/laravel-eloquent-plus
Package laravel-eloquent-plus
Short Description Supercharge your Laravel Eloquent models with automatic validation, audit trails, external IDs, smart casting, and lifecycle hooks — all with zero boilerplate.
License MIT
Homepage https://github.com/Dev-Toolbelt/laravel-eloquent-plus
Informations about the package laravel-eloquent-plus
Laravel Eloquent Plus
Supercharge your Laravel Eloquent models with automatic validation, audit trails, external IDs, smart casting, and lifecycle hooks — all with zero boilerplate.
Features
| Feature | Description |
|---|---|
| Automatic Validation | Validate model attributes before save using Laravel's validation rules |
| Audit Trail (Blamable) | Automatically track created_by, updated_by, and deleted_by |
| External ID (UUID) | Public-facing UUIDs while keeping internal integer IDs |
| Smart Auto-Casting | Infer attribute casts from validation rules automatically |
| Date Formatting | Control date output format (string or Carbon instance) |
| Lifecycle Hooks | Execute custom logic at beforeValidate, beforeSave, afterSave, beforeDelete, afterDelete |
| Hidden Attributes | Automatically hide sensitive fields like deleted_at, deleted_by |
| Custom Validators | Built-in CPF/CNPJ (Brazilian documents) and Hex Color validators |
| Custom Casts | OnlyNumbers, RemoveSpecialCharacters, UuidToIdCast |
| Cast Aliases | Register short names for custom casts like Laravel's built-in types |
Requirements
- PHP ^8.3
- Laravel ^11.0
Installation
The service provider is automatically registered via Laravel's package discovery.
Quick Start
Extend your models from ModelBase to unlock all features:
Note: Timestamp and blamable columns must be declared in
$fillable,$rules, or pre-populated in$attributesfor them to be automatically managed. Only declared columns are populated — undeclared ones are silently skipped.
That's it! Your model now has:
- Automatic validation before create/update
- Audit trail (
created_by,updated_by,deleted_by) - Soft deletes with tracking
- External UUID for public APIs
- Smart type casting inferred from rules
- Lifecycle hooks ready to use
Available Traits
Use traits individually if you don't want the full ModelBase:
| Trait | Description |
|---|---|
HasValidation |
Automatic validation with rules and auto-population of timestamps/blamable |
HasBlamable |
Track who created, updated, and deleted records |
HasExternalId |
UUID-based public identifiers |
HasAutoCasting |
Infer casts from validation rules |
HasDateFormatting |
Control date attribute output format |
HasLifecycleHooks |
Model lifecycle callbacks |
HasHiddenAttributes |
Auto-hide sensitive fields |
HasCastAliases |
Register custom cast aliases |
Validation
Define rules in your model and validation runs automatically:
Built-in Validators
| Validator | Alias | Description |
|---|---|---|
CpfCnpjValidator |
cpf_cnpj |
Validates Brazilian CPF (11 digits) or CNPJ (14 digits) |
CpfCnpjValidator |
cpf |
Validates only CPF |
CpfCnpjValidator |
cnpj |
Validates only CNPJ |
HexColor |
hex_color |
Validates hex color codes (#FFF or #FFFFFF) |
Validation Exception
When validation fails, a ValidationException is thrown with detailed error information:
Audit Trail (Blamable)
Track who performed actions on your records. Blamable is disabled by default and must be explicitly enabled per model:
Database Migration
Partial Column Support
Both blamable and timestamps support partial columns. You don't need all columns — only the ones you declare in $fillable, $rules, or $attributes will be populated. Undeclared columns are silently skipped.
Partial blamable columns:
Partial timestamp columns:
Important:
hasAttribute()checks$fillable,$rules, and$attributesto determine if a column exists on the model. It does not query the database schema. You must explicitly declare the columns your model uses.
To enforce that all expected columns exist, enable Strict Mode.
Customizing Column Names
Override the constants in your model:
External ID (UUID)
Expose UUIDs publicly while keeping integer primary keys internally:
Usage
Database Migration
Relations in toArray()
By default, when a relation is eager-loaded, Eloquent serializes its full array
representation inside toArray(). Set $addsRelationsInToArray = true on the model
to replace each loaded relation with its lightweight toSoftArray() form (only the
identifier, or the external ID when enabled). Useful for API responses where you want
to expose related records as references instead of nested payloads.
Behavior notes:
- Only loaded relations are processed — unloaded relations are not added.
- A
belongsTothat resolves tonullis preserved asnullin the output. - An empty
hasMany/hasManyThroughcollection becomes[]. - Items in a relation collection that don't extend
ModelBasefall back to their defaulttoArray()representation.
Auto-Casting
Types are automatically inferred from validation rules:
| Validation Rule | Inferred Cast |
|---|---|
boolean |
boolean |
integer |
integer |
numeric |
float |
array |
array |
date |
datetime |
date_format:Y-m-d |
date:Y-m-d |
date_format:Y-m-d H:i:s |
datetime |
Illuminate\Validation\Rules\Enum |
Enum class |
Custom Casts
Built-in Casts
| Cast | Alias | Description |
|---|---|---|
OnlyNumbers |
only_numbers |
Removes non-numeric characters |
RemoveSpecialCharacters |
remove_special_chars |
Removes special characters |
UuidToIdCast |
uuid_to_id |
Converts UUID to internal ID via lookup |
Using Casts
UuidToIdCast
Convert external UUIDs to internal IDs automatically:
Lifecycle Hooks
Execute custom logic at specific points:
Hook Execution Order
On Create:
On Update:
On Delete:
Date Formatting
Control how date attributes are returned:
Configuration
Publishing Configuration
You can publish the configuration file to customize package behavior:
This will create config/devToolbelt/eloquent-plus.php in your application.
Configuration Options
| Option | Default | Description |
|---|---|---|
blamable_field_type |
'integer' |
Type of blamable fields (created_by, updated_by, deleted_by) |
blamable_field_value |
null |
Callable to customize user identifier extraction (only for string type) |
blamable_strict_mode |
false |
Throw exception if blamable columns are missing on the model |
timestamps_strict_mode |
false |
Throw exception if timestamp columns are missing on the model |
Blamable Field Type
By default, blamable fields (created_by, updated_by, deleted_by) are validated as integers with an exists rule to ensure the user ID exists in the database.
If your application uses string-based user identifiers (like UUIDs stored as strings), you can change this:
When set to 'integer' (default):
- Validation rules:
['nullable', 'integer', 'exists:users,id'] - Ensures the user ID exists in the users table
When set to 'string':
- Validation rules:
['nullable', 'string'] - User ID is cast to string automatically
- No existence check (useful for external user systems or UUIDs)
Blamable Field Value (Custom User Identifier)
When using 'string' type, you can customize how the user identifier is retrieved using a callable:
This is useful when:
- Your users have UUID-based external IDs
- You need to store a different identifier than the primary key
- You're integrating with external authentication systems
Examples:
Strict Mode
By default, missing blamable and timestamp columns are silently skipped. If you want to enforce that all expected columns exist on your models, enable strict mode:
When strict mode is enabled, a MissingModelPropertyException is thrown if the model tries to set a column that doesn't exist:
This is useful during development to catch missing migrations early. In production, you may prefer the default behavior (false) to avoid unexpected errors.
ModelBase Constants
| Constant | Default | Description |
|---|---|---|
CREATED_AT |
'created_at' |
Created timestamp column |
UPDATED_AT |
'updated_at' |
Updated timestamp column |
DELETED_AT |
'deleted_at' |
Soft delete timestamp column |
CREATED_BY |
'created_by' |
Created by user column |
UPDATED_BY |
'updated_by' |
Updated by user column |
DELETED_BY |
'deleted_by' |
Deleted by user column |
USES_EXTERNAL_ID |
true |
Enable/disable external UUID |
EXTERNAL_ID_COLUMN |
'external_id' |
External ID column name |
ModelBase Properties
| Property | Default | Description |
|---|---|---|
$timestamps |
true |
Enable timestamps |
$dateFormat |
'Y-m-d H:i:s.u' |
Database date format |
$snakeAttributes |
false |
Snake case in serialization |
$carbonInstanceInFieldDates |
false |
Return Carbon vs string for dates |
$usesBlamable |
false |
Enable audit trail (created_by, updated_by, deleted_by) |
$addsRelationsInToArray |
false |
Replace loaded relations in toArray() with their toSoftArray() representation |
Full Example
Development
Running Tests
Running Tests with Coverage
Code Style (PSR-12)
Static Analysis (PHPStan)
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Standards
- Minimum 85% test coverage
- PSR-12 coding standards
- PHPStan level 6 compliance
License
This package is open-sourced software licensed under the MIT license.
Coverage Report
- Dashboard: Codecov
- HTML Report: GitHub Pages
Credits
- Kilderson Sena
- All Contributors
Made with by Dev Toolbelt