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




namespace App\Models;

use DevToolbelt\LaravelEloquentPlus\ModelBase;

class Product extends ModelBase
{
    protected $fillable = [
        'name',
        'price',
        'sku',
        'created_at',
        'updated_at',
        'deleted_at',
    ];

    protected array $rules = [
        'name' => ['

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
    ];
}

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->timestamps();
    $table->softDeletes();

    // Blamable columns
    $table->foreignId('created_by')->constrained('users');
    $table->foreignId('updated_by')->nullable()->constrained('users');
    $table->foreignId('deleted_by')->nullable()->constrained('users');
});

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', ...]

Schema::create('orders', function (Blueprint $table) {
    $table->id();
    $table->uuid('external_id')->unique();
    $table->decimal('total', 10, 2);
    $table->timestamps();
});

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);
    }
}

$order = Order::with(['product', 'items'])->find(1);

$order->toArray();
// [
//     'id' => '...',
//     'total' => 99.99,
//     'product' => ['id' => '550e8400-...'],          // toSoftArray()
//     'items'   => [['id' => 10], ['id' => 11]],      // collection of toSoftArray()
// ]

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}");
    }
}

class Event extends ModelBase
{
    // Return dates as formatted strings (default)
    protected bool $carbonInstanceInFieldDates = false;

    // Or return Carbon instances
    protected bool $carbonInstanceInFieldDates = true;

    protected array $rules = [
        'starts_at' => ['

$event->starts_at; // "2024-01-15 10:00:00" (string, when $carbonInstanceInFieldDates = false)
$event->starts_at; // Carbon instance (when $carbonInstanceInFieldDates = true)

// 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}",

// config/devToolbelt/eloquent-plus.php
return [
    'blamable_strict_mode' => true,
    'timestamps_strict_mode' => true,
];

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 



namespace App\Models;

use DevToolbelt\LaravelEloquentPlus\ModelBase;
use App\Enums\OrderStatus;

class Order extends ModelBase
{
    protected bool $usesBlamable = true;

    protected $fillable = [
        'customer_id',
        'status',
        'total',
        'notes',
        'delivered_at',
        'created_at',
        'updated_at',
        'deleted_at',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    protected array $rules = [
        'customer_id' => ['           $this->delivered_at = now();
        }
    }
}
bash
php artisan vendor:publish --tag=eloquent-plus-config