amerald/eloquent-toolkit

为Eloquent带来属性验证和其他酷炫功能

dev-master 2021-02-10 16:11 UTC

This package is auto-updated.

Last update: 2024-09-11 00:35:19 UTC


README

享受Eloquent属性验证和其他酷炫功能。

安装

composer require amerald/eloquent-toolkit

用法

属性验证

Laravel的验证非常出色。尽管如此,验证后的数据并不总是直接应用于Eloquent模型:我们可能需要以某种方式转换它,甚至从多个数据源组合一个模型。

如果我们可以以类似于函数参数的方式验证模型属性,指定属性是否必需以及其类型(s)将会是多么美好?

<?php

use Illuminate\Database\Eloquent\Model;
use Amerald\Eloquent\Traits\ValidatesAttributes;

class Post extends Model
{
    use ValidatesAttributes;
    
    protected function rules(): array
    {
        return [
            'title' => 'required|string',
            'body' => 'required|string',
            'image' => 'nullable|string',
        ];
    }
}

有一些验证选项。在每种情况下,如果验证失败,将抛出 Amerald\Eloquent\Exceptions\AttributeValidationException

Amerald\Eloquent\Exceptions\AttributeValidationException: 
The title field is required.
The body field is required.
The image must be a string.

自动验证

默认情况下,在 saving 事件上执行自动化

运行时验证

当启用运行时验证时,在设置/获取属性时立即验证。每次都会构造一个新的验证器实例。

运行时验证默认启用。可以通过调用静态方法 disableRuntimeValidation() 来禁用它。

$post = new Post();
$post->title = false; // trying to set an invalid type
dump($post->body); // trying to access a required attribute that currently is null

手动验证

Post::disableRuntimeValidation();

$post = Post::make([
    'title' => null,
    'body' => null,
    'image' => null,
]);

$post->validate();

生成UUID

例如,我们需要为我们的主键字段 id 生成一个UUID

<?php

use Illuminate\Database\Eloquent\Model;
use Amerald\Eloquent\Traits\GeneratesUUID;

class Post extends Model
{
    use GeneratesUUID;
    
    public $incrementing = false;
    
    public $timestamps = false;
}

UUID将在 'creating' 事件上 仅生成一次

可以为多个列生成UUID

class Post extends Model
{
    use GeneratesUUID;
    
    public $incrementing = false;
        
    public $timestamps = false;
    
    public function uuidColumns(): array
    {
        return [
            'id',
            'custom_column'
        ];
    }
}