PHP code example of dev-toolbelt / laravel-eloquent-plus
1. Go to this page and download the library: Download dev-toolbelt/laravel-eloquent-plus library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dev-toolbelt / laravel-eloquent-plus example snippets
use Illuminate\Database\Eloquent\Model;
use DevToolbelt\LaravelEloquentPlus\Concerns\HasValidation;
use DevToolbelt\LaravelEloquentPlus\Concerns\HasBlamable;
class MyModel extends Model
{
use HasValidation;
use HasBlamable;
// ...
}
class User extends ModelBase
{
protected array $rules = [
'name' => ['' => ['
use DevToolbelt\LaravelEloquentPlus\Exceptions\ValidationException;
try {
$user->save();
} catch (ValidationException $e) {
$e->getErrors(); // All errors as array
$e->getMessages(); // All error messages
$e->hasErrorFor('email'); // Check specific field
$e->getFirstMessageFor('email'); // Get first error message
}
class Post extends ModelBase
{
// Enable blamable audit tracking
protected bool $usesBlamable = true;
protected $fillable = [
'title',
'created_at',
'updated_at',
'deleted_at',
// Declare blamable columns to enable automatic population:
'created_by', // Set on create (authenticated user ID)
'updated_by', // Set on create and update
'deleted_by', // Set on soft delete
];
}
class Comment extends ModelBase
{
protected bool $usesBlamable = true;
protected $fillable = [
'body',
'created_by', // Only track who created
'created_at',
'updated_at',
'deleted_at',
];
// updated_by and deleted_by are not declared,
// so they will be silently skipped.
}
class EventLog extends ModelBase
{
protected $fillable = [
'event',
'created_at', // Only track creation time
];
// updated_at is not declared, so it will be silently skipped
// even though $timestamps = true.
}
class Post extends ModelBase
{
public const string CREATED_BY = 'author_id';
public const string UPDATED_BY = 'editor_id';
public const string DELETED_BY = 'remover_id';
}
class Order extends ModelBase
{
// Enable external ID (enabled by default)
public const bool USES_EXTERNAL_ID = true;
public const string EXTERNAL_ID_COLUMN = 'external_id';
}
$order = Order::create(['total' => 99.99]);
// Internal ID (hidden from serialization)
$order->id; // 1
// External UUID (exposed in API responses)
$order->getExternalId(); // "550e8400-e29b-41d4-a716-446655440000"
// Find by external ID
$order = Order::findByExternalId('550e8400-e29b-41d4-a716-446655440000');
$order = Order::findByExternalIdOrFail('550e8400-e29b-41d4-a716-446655440000');
// API response automatically uses UUID as "id"
$order->toArray(); // ['id' => '550e8400-e29b-41d4-a716-446655440000', ...]
class Order extends ModelBase
{
public $addsRelationsInToArray = true;
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
public function items(): HasMany
{
return $this->hasMany(OrderItem::class);
}
}
class Product extends ModelBase
{
protected array $rules = [
'active' => ['boolean'], // Cast to boolean
'quantity' => ['integer'], // Cast to integer
'price' => ['numeric'], // Cast to float
'tags' => ['array'], // Cast to array
'expires_at' => ['date'], // Cast to datetime
];
// No need to define $casts - it's automatic!
}
class Customer extends ModelBase
{
protected $casts = [
// Using aliases (short names)
'phone' => 'only_numbers',
'name' => 'remove_special_chars',
'category_id' => 'uuid_to_id:categories,external_id',
// Or using full class names
'document' => \DevToolbelt\LaravelEloquentPlus\Casts\OnlyNumbers::class,
];
}
// When you receive a UUID from the API
$order->category_id = '550e8400-e29b-41d4-a716-446655440000';
// It's automatically converted to the internal ID
$order->category_id; // 42 (the actual ID from categories table)
class Invoice extends ModelBase
{
protected function beforeValidate(): void
{
// Normalize data before validation
$this->number = strtoupper($this->number);
}
protected function beforeSave(): void
{
// Logic after validation, before database write
$this->total = $this->calculateTotal();
}
protected function afterSave(): void
{
// Logic after persisting to database
event(new InvoiceSaved($this));
}
protected function beforeDelete(): void
{
// Cleanup before deletion
$this->items()->delete();
}
protected function afterDelete(): void
{
// Logic after deletion
Cache::forget("invoice:{$this->id}");
}
}
// config/devToolbelt/eloquent-plus.php
return [
'blamable_field_type' => 'string', // Use 'string' for UUID or other string identifiers
];
// config/devToolbelt/eloquent-plus.php
return [
'blamable_field_type' => 'string',
// Use external_id instead of the default user ID
'blamable_field_value' => fn($user) => $user->external_id,
];
// Use external UUID
'blamable_field_value' => fn($user) => $user->external_id,
// Use email as identifier
'blamable_field_value' => fn($user) => $user->email,
// Use a formatted string
'blamable_field_value' => fn($user) => "user:{$user->id}",
use DevToolbelt\LaravelEloquentPlus\Exceptions\MissingModelPropertyException;
// With blamable_strict_mode = true
// If the table is missing the 'created_by' column:
try {
$post->save();
} catch (MissingModelPropertyException $e) {
// 'The property "created_by" is